0
点赞
收藏
分享

微信扫一扫

Java list 去重

江南北 2021-09-23 阅读 130
Java 开发
  1. 去除List中重复的 String
List unique = list.stream().distinct().collect(Collectors.toList());
  1. 去除List中重复的对象

Person 对象:

public class Person {
    private String id;
    private String name;
    private String city;
}

根据name去重:

List<Person> unique = persons.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);

根据name, city两个属性去重:

List<Person> unique = persons.stream().collect(
           Collectors. collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getCity()))), ArrayList::new)
);
举报

相关推荐

0 条评论