Java 8按属性区分在Java 8中,如何使用Stream通过检查每个对象的属性的区别性来实现API?例如,我有一个列表Person对象,并且我想删除同名的人,persons.stream().distinct();将使用默认的等式检查。Person所以我需要类似的东西,persons.stream().distinct(p -> p.getName());不幸的是distinct()方法没有这样的重载。中不修改相等检查。Person类可以简洁地做到这一点吗?
3 回答
largeQ
TA贡献2039条经验 获得超8个赞
distinct
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));}persons.stream().filter(distinctByKey(Person::getName))
distinct()
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
persons.collect(toMap(Person::getName, p -> p, (p, q) -> p)).values();
翻翻过去那场雪
TA贡献2065条经验 获得超14个赞
persons.stream() .map(Wrapper::new) .distinct() .map(Wrapper::unwrap) ...;
Wrapper
class Wrapper {
private final Person person;
public Wrapper(Person person) {
this.person = person;
}
public Person unwrap() {
return person;
}
public boolean equals(Object other) {
if (other instanceof Wrapper) {
return ((Wrapper) other).person.getName().equals(person.getName());
} else {
return false;
}
}
public int hashCode() {
return person.getName().hashCode();
}}添加回答
举报
0/150
提交
取消
