Stream and the distinct operation(流和不同的操作)
问题描述
我有以下代码:
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());
但我不明白为什么 distinct 返回 3 而不是 2.
but I don't understand why distinct returns 3 and not 2.
推荐答案
您还需要覆盖 C 类中的 hashCode 方法.例如:
You need to also override the hashCode method in class C. For example:
@Override
public int hashCode() {
return n.hashCode();
}
当两个 C 对象相等时,它们的 hashCode 方法必须返回相同的值.
When two C objects are equal, their hashCode methods must return the same value.
接口Stream的API文档没有提到这一点,但是众所周知,如果你重写equals,你也应该重写hashCode.Object.equals() 的 API 文档提到了这一点:
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:
请注意,每当重写 hashCode 方法时,通常都需要重写该方法,以维护 hashCode 方法的一般约定,该约定声明等于对象必须具有相同的哈希码.
Note that it is generally necessary to override the
hashCodemethod whenever this method is overridden, so as to maintain the general contract for thehashCodemethod, which states that equal objects must have equal hash codes.
显然,Stream.distinct() 确实使用了对象的哈希码,因为当你像我上面展示的那样实现它时,你会得到预期的结果:2.
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.
这篇关于流和不同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:流和不同的操作
基础教程推荐
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
