通过groupingBy 与Function做筛选
// 方法
public static <E, R> List<E> getDuplicateElements(List<E> list, Function<E, R> function) {
Map<R, List<E>> collect = list.stream().collect(Collectors.groupingBy(function));
return collect.entrySet().stream().filter(entry -> entry.getValue().size() > 1).flatMap(entry -> entry.getValue().stream()).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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
List<User> list = new ArrayList<>();
list.add(new User(1, "1"));
list.add(new User(1, "2"));
list.add(new User(2, "3"));
list.add(new User(3, "3"));
List<User> duplicateElements = getDuplicateElements(list, user -> user.id);
System.out.println(duplicateElements);
}