流和不同的操作

xde*_*000 30 java java-8 java-stream

我有以下代码:

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());
Run Code Online (Sandbox Code Playgroud)

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

Jes*_*per 46

您还需要覆盖hashCode类中的方法C.例如:

@Override
public int hashCode() {
    return n.hashCode();
}
Run Code Online (Sandbox Code Playgroud)

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

接口的API文档Stream没有提到这一点,但众所周知,如果你覆盖equals,你也应该覆盖hashCode.API文档Object.equals()提到:

请注意,通常需要在重写此hashCode方法时覆盖该方法,以便维护该hashCode方法的常规协定,该协定声明相等的对象必须具有相等的哈希代码.

显然,Stream.distinct()确实使用了对象的哈希码,因为当你像我上面展示的那样实现它时,你会得到预期的结果:2.

  • +1你提到的规则非常重要,不要覆盖 equals 或 hashcode 除非你覆盖两者。这可能会导致编译时错误。 (2认同)