自定义比较器,一个key判断是否存在于一组容器中

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;
            }
        });
    }

开源google的guava包下,Maps,Sets系列工具类,有contains(Key)与上述功能相同,简洁代码,效率应该也更高,学无止境,幸得高人指点。

猜你喜欢

转载自my.oschina.net/u/3744350/blog/1619662
今日推荐