Custom comparator, a key to determine whether it exists in a set of containers

private static int fieldCompare(String key, String[] keys) {
        return Objects.compare(key, keys, new Comparator<Object>() {
            public int compare(Object o1, Object o2) {
                String key1 = null;
                String[] keys1 = null;
                if (o1 instanceof String) {
                    key1 = (String) o1;
                }
                if (o2 instanceof String[]) {
                    keys1 = (String[]) o2;
                }

                if (key1 == null || keys1 == null) {
                    return -1;
                }

                for (String m : keys1) {
                    if (m.equals(key1)) {
                        return 0;
                    }
                }
                return -1;
            }
        });
    }

 

Under the guava package of open source google, the Maps, Sets series of tool classes have contains(Key) which is the same as the above function, the code is concise, the efficiency should be higher, and the learning is endless.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325478854&siteId=291194637