如何使用流API从java中的对象列表中删除重复项
我已经找到了一个解决方案,可以从列表中删除重复项 使用流API
我只发现了这个问题 How to remove duplicates from list of objects by id
我有一个需要按人名筛选的人的列表,尝试使用下面的代码段,但它不按人名筛选
private static Map<Person, Integer> getUniqueByBiggerId(Collection<Person> persons) {
return persons.stream().collect(Collectors.toMap(
persons ->
persons,
Person::getId,
(id1, id2) -> {
if (id2 > id1)
return id2;
else
return id1;
}
));
}
public static void main(String args[]){
//.........
List<Person> Persons
= Arrays.asList(Person1, Person2,Person2,Person1,Person2, Person1);
getUniqueByBiggerId(Persons);
}
# 1 楼答案
假设您有一个
Person
类,该类包含字段id
和name
,并且字段id
是您要筛选的字段,您只需要重写equals和hashCode方法:然后你可以创建一个列表:
要消除重复,只需写下:
List<Person> collect = people.stream().distinct().collect(Collectors.toList());
System.out.println(collect.size());
这将产生输出2
# 2 楼答案
您非常接近解决方案:
输出:
# 3 楼答案