- 去除List中重复的 String
List unique = list.stream().distinct().collect(Collectors.toList());
- 去除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)
);
网友评论