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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:07:02  来源:igfitidea点击:

Stream and the distinct operation

javajava-8java-stream

提问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 distinctreturns 3 and not 2.

但我不明白为什么distinct返回 3 而不是 2。

采纳答案by Jesper

You need to also override the hashCodemethod in class C. For example:

您还需要覆盖hashCodeclass 中的方法C。例如:

@Override
public int hashCode() {
    return n.hashCode();
}

When two Cobjects are equal, their hashCodemethods must return the same value.

当两个C对象相等时,它们的hashCode方法必须返回相同的值。

The API documentation for interface Streamdoes 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 hashCodemethod whenever this method is overridden, so as to maintain the general contract for the hashCodemethod, 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。