gpt4 book ai didi

java - 基于 Java 8 中的属性从对象列表中删除重复项

转载 作者:IT老高 更新时间:2023-10-28 20:25:41 28 4
gpt4 key购买 nike

我正在尝试根据某些属性从对象列表中删除重复项。

我们可以使用 java 8 以简单的方式做到这一点

List<Employee> employee

我们可以根据员工的 id 属性从中删除重复项吗?我已经看到从字符串数组列表中删除重复字符串的帖子。

最佳答案

您可以从 List 中获取一个流并将其放入 TreeSet 中,您可以从中提供一个自定义比较器来唯一地比较 id。

如果你真的需要一个列表,你可以把这个集合放回一个 ArrayList。

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

...
List<Employee> unique = employee.stream()
.collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingInt(Employee::getId))),
ArrayList::new));

举个例子:

List<Employee> employee = Arrays.asList(new Employee(1, "John"), new Employee(1, "Bob"), new Employee(2, "Alice"));

它会输出:

[Employee{id=1, name='John'}, Employee{id=2, name='Alice'}]

另一个想法可能是使用一个包装器来包装员工,并使用基于其 id 的 equals 和 hashcode 方法:

class WrapperEmployee {
private Employee e;

public WrapperEmployee(Employee e) {
this.e = e;
}

public Employee unwrap() {
return this.e;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WrapperEmployee that = (WrapperEmployee) o;
return Objects.equals(e.getId(), that.e.getId());
}

@Override
public int hashCode() {
return Objects.hash(e.getId());
}
}

然后你包装每个实例,调用 distinct(),解开它们并将结果收集到一个列表中。

List<Employee> unique = employee.stream()
.map(WrapperEmployee::new)
.distinct()
.map(WrapperEmployee::unwrap)
.collect(Collectors.toList());

事实上,我认为你可以通过提供一个进行比较的函数来使这个包装器通用:

public class Wrapper<T, U> {
private T t;
private Function<T, U> equalityFunction;

public Wrapper(T t, Function<T, U> equalityFunction) {
this.t = t;
this.equalityFunction = equalityFunction;
}

public T unwrap() {
return this.t;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@SuppressWarnings("unchecked")
Wrapper<T, U> that = (Wrapper<T, U>) o;
return Objects.equals(equalityFunction.apply(this.t), that.equalityFunction.apply(that.t));
}

@Override
public int hashCode() {
return Objects.hash(equalityFunction.apply(this.t));
}
}

映射将是:

.map(e -> new Wrapper<>(e, Employee::getId))

关于java - 基于 Java 8 中的属性从对象列表中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670116/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com