Java 流和不同的操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21333646/
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
Stream and the distinct operation
提问by xdevel2000
I have the following code:
我有以下代码:
class C
{
String n;
C(String n)
{
this.n = n;
}
public String getN() { return n; }
@Override
public boolean equals(Object obj)
{
return this.getN().equals(((C)obj).getN());
}
}
List<C> cc = Arrays.asList(new C("ONE"), new C("TWO"), new C("ONE"));
System.out.println(cc.parallelStream().distinct().count());
but I don't understand why distinct
returns 3 and not 2.
但我不明白为什么distinct
返回 3 而不是 2。
采纳答案by Jesper
You need to also override the hashCode
method in class C
. For example:
您还需要覆盖hashCode
class 中的方法C
。例如:
@Override
public int hashCode() {
return n.hashCode();
}
When two C
objects are equal, their hashCode
methods must return the same value.
当两个C
对象相等时,它们的hashCode
方法必须返回相同的值。
The API documentation for interface Stream
does not mention this, but it's well-known that if you override equals
, you should also override hashCode
. The API documentation for Object.equals()
mentions this:
interface 的 API 文档Stream
没有提到这一点,但众所周知,如果您覆盖equals
,您也应该覆盖hashCode
. API 文档中Object.equals()
提到了这一点:
Note that it is generally necessary to override the
hashCode
method whenever this method is overridden, so as to maintain the general contract for thehashCode
method, which states that equal objects must have equal hash codes.
请注意,
hashCode
每当重写此方法时,通常都需要重写该方法,以维护该hashCode
方法的通用约定,即相等的对象必须具有相等的哈希码。
Apparently, Stream.distinct()
indeed uses the hash code of the objects, because when you implement it like I showed above, you get the expected result: 2.
显然,Stream.distinct()
确实使用了对象的哈希码,因为当你像我上面展示的那样实现它时,你会得到预期的结果:2。