Java list 去重

江南北

关注

阅读 130

2021-09-23

  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)

0 0 举报