JAVA8 获取list集合中重复的元素和获取去重数据

1.java8获取list集合中重复的元素

      //单独String集合
        List<String> list = Arrays.asList("a","b","a","c","d","b");
        List<String> collect = list.stream().filter(i -> i != "")               // list 对应的 Stream 并过滤""
                .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数
                .entrySet()
                .stream()                       // 所有 entry 对应的 Stream
                .filter(e -> e.getValue() > 1)         // 过滤出元素出现次数大于 1 (重复元素)的 entry
                .map(Map.Entry::getKey)                // 获得 entry 的键(重复元素)对应的 Stream
                .collect(Collectors.toList());
        System.out.println(collect);

2.java8根据List对象属性获取重复数据和获取去重后数据

2.1获取重复数据

List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("张三", 8, 3000));
        personList.add(new Person("李四", 18, 5000));
        personList.add(new Person("王五", 28, 7000));
        personList.add(new Person("孙六", 38, 9000));
        personList.add(new Person("孙六", 38, 9000));
        personList.add(new Person("孙六", 38, 10000));
        
       //1.先根据得到一个属于集合 姓名
        List<String> uniqueList = personList.stream().collect(Collectors.groupingBy(Person::getName, Collectors.counting()))
                .entrySet().stream().filter(e -> e.getValue() > 1)
                .map(Map.Entry::getKey).collect(Collectors.toList());
        uniqueList.forEach(p -> System.out.println(p));

        //计算两个list中的重复值  3条数据
        List<Person> reduce1 = personList.stream().filter(item -> uniqueList.contains(item.getName())).collect(Collectors.toList());
        System.out.println(reduce1.toString());
   
        //2.根据多个属性获取重复数据,只能重复操作得到重复的数据 工资
        List<Integer> collect1 = reduce1.stream().collect(Collectors.groupingBy(Person::getWages, Collectors.counting()))
                .entrySet().stream().filter(e -> e.getValue() > 1)
                .map(Map.Entry::getKey).collect(Collectors.toList());

        //计算两个list中的差集
        List<Person> collect2 = reduce1.stream().filter(item -> collect1.contains(item.getWages())).collect(Collectors.toList());
        System.out.println(collect2.toString());

2.2获取去重后数据

List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("张三", 8, 3000));
        personList.add(new Person("李四", 18, 5000));
        personList.add(new Person("王五", 28, 7000));
        personList.add(new Person("孙六", 38, 9000));
        personList.add(new Person("孙六", 38, 9000));
        personList.add(new Person("孙六", 38, 10000));
       
 //去重      
 List<Person> unique = personList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));
        System.out.println("unique:"+unique.toString());

== 感谢大佬:https://blog.csdn.net/qq_41128049/article/details/127129690==

猜你喜欢

转载自blog.csdn.net/csl12919/article/details/130538696