Java list 去重

2021-04-20  本文已影响0人  _浅墨_
  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)
);
上一篇 下一篇

猜你喜欢

热点阅读