Java8 Streams - 使用 Stream Distinct 删除重复项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27911406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java8 Streams - Remove Duplicates With Stream Distinct
提问by Matt Klooster
I have a stream such as:
我有一个流,例如:
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.
我想删除以相同字母开头的名称,以便只留下一个以该字母开头的名称(与哪个无关)。
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?
我试图了解该distinct()
方法的工作原理。我在文档中读到它基于对象的“equals”方法。但是,当我尝试包装 String 时,我注意到从未调用过 equals 方法并且没有删除任何内容。有什么我在这里想念的吗?
Wrapper Class:
包装类:
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);
}
}
And some simple code:
还有一些简单的代码:
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);
}
采纳答案by Louis Wasserman
Whenever you override equals
, you also need to override the hashCode()
method, which will be used in the implementation of distinct()
.
每当您覆盖 时equals
,您还需要覆盖该hashCode()
方法,该方法将在 的实现中使用distinct()
。
In this case, you could just use
在这种情况下,您可以使用
@Override public int hashCode() {
return test.charAt(0);
}
...which would work just fine.
...这会工作得很好。
回答by Sujit Kamthe
Alternative approach
替代方法
String[] array = {"matt", "jason", "michael"};
Arrays.stream(array)
.map(name-> name.charAt(0))
.distinct()
.map(ch -> Arrays.stream(array).filter(name->name.charAt(0) == ch).findAny().get())
.forEach(System.out::println);