stream去重_使用Java Stream API中DistinctBy删除重复数据
Stream API提供distinct()方法,該方法基于數據Object類的equals()方法返回列表的不同元素。下面先做一個數據Object類,用來發現重復數據:
public class LegacyObject {
private final UUID id;
private final String foo;
private final int bar;
public LegacyObject(UUID id, String foo, int bar) {
this.id = id;
this.foo = foo;
this.bar = bar;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
// Implementation of equals() using only the id field
// Getters
}
public class DeduplicateWrapper {
private final LegacyObject object;
public DeduplicateWrapper(LegacyObject object) {
this.object = object;
}
public LegacyObject getObject() {
return object;
}
@Override
public int hashCode() {
return Objects.hash(object.getFoo());
}
// Implementation of equals() using only the foo field of the wrapped object
}
使用流API重復刪除集合:
List duplicates = ...;
duplicates.stream()
.map(DeduplicateWrapper::new)
.distinct()
.map(DeduplicateWrapper::getObject);
不使用Stream的Java8之前代碼
List deduplicated = new ArrayList<>();
Set wrappers = new HashSet<>();
for (LegacyObject duplicate: duplicates) {
wrappers.add(new DeduplicateWrapper(duplicate));
}
for (DeduplicateWrapper wrapper: wrappers) {
deduplicated.add(wrapper.getObject());
}
如果你足夠幸運能夠使用Kotlin:
val duplicates: List = ...
duplicates.distinctBy { it.foo }
總結
以上是生活随笔為你收集整理的stream去重_使用Java Stream API中DistinctBy删除重复数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python元祖用法_Python序列(
- 下一篇: Linux连接xshell时连不上的问题