集合去重复及取重复及stream的使用

stream适合统计和查询,遍历把每个元素的数量放到map里, 然后map去除数量大于1的
public class test69 {

    public static void main(String[] args) {
        //取出重复的数据
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(1);
        list.add(2);
        Map<Integer, Long> countMap = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<Integer> flag = countMap.keySet().stream().filter(key -> countMap.get(key) > 1).distinct().collect(Collectors.toList());
        System.out.println(flag);
    }

}
countMap.get(key) > 1)就是数量大于1的元素所以是重复的元素:
[1, 2]

Process finished with exit code 0

不重复也是一样算的:

public class test67 {

    public static void main(String[] args) {
        //取出不重复的数据
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(1);
        list.add(2);
        Map<Integer, Long> countMap = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<Integer> flag = countMap.keySet().stream().filter(key -> countMap.get(key) == 1).distinct().collect(Collectors.toList());
        System.out.println(flag);
    }

}
[3, 4]

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/weixin_45029766/article/details/104907213
今日推荐