【Stream 笔记】使用Stream查询List当中实体的某个属性重复值有哪些

使用groupingBy做分组

// 方法
public static <E, R> List<R> getDuplicateValue(List<E> list, Function<E, R> function) {

        Map<R, Long> frequencies = list.stream().collect(Collectors.groupingBy(function, Collectors.counting()));
        return frequencies.entrySet().stream()
                .filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()).collect(Collectors.toList());

    }

// 调用
    void contextLoads() {
        class User {
            public Integer id;
            public String name;

            public User(Integer id, String name) {
                this.id = id;
                this.name = name;
            }

        }
        List<User> list = new ArrayList<>();
        list.add(new User(1, "张三"));
        list.add(new User(1, "李四"));
        list.add(new User(2, "王五"));
        list.add(new User(3, "李四"));

        // 查看重复的id
        List<Integer> duplicateId = getDuplicateValue(list, user -> user.id);
        System.out.println(duplicateId);
        // 查看重复的名字
        List<String> duplicateName = getDuplicateValue(list, user -> user.name);
        System.out.println(duplicateName);
    }

你可能感兴趣的:(stream,java)