根据属性获取List集合中重复的元素

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class Person{
        private String name;
        private Integer age;
        private Integer wages;

    }



    @Test
    void contextLoads() {
        List personList = new ArrayList();
        personList.add(new Person("张三", 8, 3000));
        personList.add(new Person("李四", 8, 5000));
        personList.add(new Person("王五", 28, 7000));
        personList.add(new Person("孙六1", 38, 1));
        personList.add(new Person("孙六", 39, 2));
        personList.add(new Person("孙六", 40, 3));
        personList.add(new Person("孙七", 41, 4));
        personList.add(new Person("孙七", 42, 5));

        //1.先根据得到一个属于集合
        List 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));

        //2.计算两个list中的重复值
        List reduce1 = personList.stream().filter(item -> uniqueList.contains(item.getName())).collect(Collectors.toList());
        reduce1.forEach(System.out::println);


    } 
  

你可能感兴趣的:(java)