Java8 Streams - Remove Duplicates With Stream Distinct(Java8 Streams - 使用 Stream Distinct 删除重复项)
问题描述
我有一个流,例如:
Arrays.stream(new String[]{"matt", "jason", "michael"});
我想删除以相同字母开头的名称,以便只剩下一个以该字母开头的名称(不管是哪个).
I would like to remove names that begin with the same letter so that only one name (doesn't matter which) beginning with that letter is left.
我试图了解 distinct()
方法有效.我在文档中读到它基于对象的equals"方法.但是,当我尝试包装 String 时,我注意到 equals 方法从未被调用,并且没有任何内容被删除.我这里有什么遗漏吗?
I'm trying to understand how the distinct()
method works. I read in the documentation that it's based on the "equals" method of an object. However, when I try wrapping the String, I notice that the equals method is never called and nothing is removed. Is there something I'm missing here?
包装类:
static class Wrp {
String test;
Wrp(String s){
this.test = s;
}
@Override
public boolean equals(Object other){
return this.test.charAt(0) == ((Wrp) other).test.charAt(0);
}
}
还有一些简单的代码:
public static void main(String[] args) {
Arrays.stream(new String[]{"matt", "jason", "michael"})
.map(Wrp::new)
.distinct()
.map(wrp -> wrp.test)
.forEach(System.out::println);
}
推荐答案
当你重写 equals
时,你还需要重写 hashCode()
方法,这将是用于distinct()
的实现.
Whenever you override equals
, you also need to override the hashCode()
method, which will be used in the implementation of distinct()
.
在这种情况下,您可以使用
In this case, you could just use
@Override public int hashCode() {
return test.charAt(0);
}
...这样就可以了.
这篇关于Java8 Streams - 使用 Stream Distinct 删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java8 Streams - 使用 Stream Distinct 删除重复项
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01