多个String集合取交集

	/**
     * 多个String集合取交集
     *
     * @param values
     * @return
     */
    public static Set<String> intersectStringList(List<String>... values) {
    
    
        Map<Integer, Set<String>> map = new HashMap<>(8);
        int index = 1;
        Set<String> result = new HashSet<>(8);
        for (List<String> value : values) {
    
    
            if (value != null) {
    
    
                map.put(index++, new HashSet<>(value));
            }
            if (value != null && value.isEmpty()) {
    
    
                return result;
            }
        }
        boolean first = true;
        for (Integer value : map.keySet()) {
    
    
            if (first) {
    
    
                result.addAll(map.get(value));
                first = false;
            }
            result.retainAll(map.get(value));
        }
        return result;
    }

    public static void main(String[] args) {
    
    
        List<String> list1 = Stream.of("1", "b", "3").collect(Collectors.toList());
        List<String> list2 = Stream.of("a", "b", "c").collect(Collectors.toList());
        List<String> list3 = Stream.of("b", "2", "3").collect(Collectors.toList());
        System.out.println(intersectStringList(list1, list2, list3));
    }

返回结果:

[b]

猜你喜欢

转载自blog.csdn.net/iloki/article/details/113932216