java list 对象根据某个字段去重的方法

 List<User> lists = new ArrayList<>();
for (int i = 0; i < 40000; i++) {
if (i%2 == 0){
lists.add(new User("aa1",1));
}else {
lists.add(new User("aa2",2));
}

}
lists = lists.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(User::getAge))), ArrayList::new));
for (int i = 0; i < lists.size(); i++) {
System.out.println(lists.get(i).getName());
}
posted @ 2021-06-17 17:37  凌波漫步~  阅读(3932)  评论(0编辑  收藏  举报