当前位置: 首页 > 知识库问答 >
问题:

distinct()方法不为HashSet元素流返回不同的元素

沈英勋
2023-03-14

假设我有一个Employee类,它具有正确重写的equals和hashcode方法。

public class Employee {

private int eno;
private String firstName;
private String lastName;

@Override
public int hashCode() {
    System.out.println("hashcode called");
    final int prime = 31;
    int result = 1;
    result = prime * result + eno;
    result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
    result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    System.out.println("equals called");
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Employee other = (Employee) obj;
    if (eno != other.eno)
        return false;
    if (firstName == null) {
        if (other.firstName != null)
            return false;
    } else if (!firstName.equals(other.firstName))
        return false;
    if (lastName == null) {
        if (other.lastName != null)
            return false;
    } else if (!lastName.equals(other.lastName))
        return false;
    return true;
}
}

测试类如下所示

class Test {

    public static void main(String[] args) {

        Employee e1 = new Employee(1, "Karan", "Mehara");
        Employee e2 = new Employee(2, "Rajesh", "Shukla");

        Set<Employee> emps= new HashSet<>();
        emps.add(e1);
        emps.add(e2);
        System.out.println(emps);

        // No such requirement just for testing purpose modifying 
        e2.setEno(1);
        e2.setFirstName("Karan");
        e2.setLastName("Mehara");

        System.out.println(emps);

        emps.stream().distinct().forEach(System.out::println);
    }

}

上述程序的输出为:

员工[ENO=1,FirstName=Karan,LastName=Mehara]

为什么distinct()方法返回重复的元素?

根据employee类的equals()和hashcode()方法,这两个对象是相同的。

/**
     * Returns a stream consisting of the distinct elements (according to
     * {@link Object#equals(Object)}) of this stream.
     *
     * <p>For ordered streams, the selection of distinct elements is stable
     * (for duplicated elements, the element appearing first in the encounter
     * order is preserved.)  For unordered streams, no stability guarantees
     * are made.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">stateful
     * intermediate operation</a>.
     *
     * @apiNote
     * Preserving stability for {@code distinct()} in parallel pipelines is
     * relatively expensive (requires that the operation act as a full barrier,
     * with substantial buffering overhead), and stability is often not needed.
     * Using an unordered stream source (such as {@link #generate(Supplier)})
     * or removing the ordering constraint with {@link #unordered()} may result
     * in significantly more efficient execution for {@code distinct()} in parallel
     * pipelines, if the semantics of your situation permit.  If consistency
     * with encounter order is required, and you are experiencing poor performance
     * or memory utilization with {@code distinct()} in parallel pipelines,
     * switching to sequential execution with {@link #sequential()} may improve
     * performance.
     *
     * @return the new stream
     */
    Stream<T> distinct();

共有1个答案

岳毅
2023-03-14

被定义为“不包含重复元素的集合”。因此,streamdistinct方法很可能被实现为完全不执行任何操作,因为它已经保证值是唯一的。

javadoc:

注意:如果使用可变对象作为集合元素,则必须非常小心。如果对象是集合中的一个元素,而对象的值以影响相等比较的方式更改,则不指定集合的行为。这种禁止的一个特殊情况是,不允许一个集合将自身包含为一个元素。

 类似资料:
  • 所以我正在尝试制作一个程序,它将使用HashMap计算一个唯一单词出现在一个小文件中的次数。但是,当我尝试通过在我的HashMap上使用. get(key)来增加重复单词的计数时,它返回true而不是我想要转换为的整数值。如何让我的代码返回值而不是布尔值?这是我到目前为止的代码: 我的FindCommons类: 导入java。util。ArrayList;公共类FindCommons{ }

  • 我有一个xml。我想要元素

  • 请帮我检查数据库属性。 然后,sizeBinding有第一个元素null(用于宽度)和绑定表达式实例(用于高度绑定)。我可以使用Mode=twoway设置绑定,但是我想知道为什么如果Mode没有设置为twoway就不会创建绑定实例。我认为这是因为表达式需要比路径更复杂。但是,我尝试了,但是返回null作为绑定。我尝试了GetBinding*方法,但它们的行为与完全相同。 我谷歌搜索的唯一一个问题就

  • 有一个简单的: 以及任务对象的列表。如何通过使用获得每个作为的列表。我试过这个: 但它返回

  • 我正在自学Hadoop和Map Reduce编程模型。我试图理解它的核心元素:我试图将下面的每个元素与下面的特性相匹配: 减速器 组合器 洗牌和排序 映射器 分区器 复制

  • 问题内容: 是否有直接函数来计算CosmosDb查询中的不同元素? 这是默认计数: 和无数的独特作品: 但这会返回错误的请求-语法错误: 会和他们一起工作吗? 问题答案: 这是另一个解决地区问题并适用于的查询。基本上,您需要封装不重复内容然后进行计数。我们已经通过分页对它进行了测试,以查找您想要唯一记录的情况,而不仅是计数,而且它正在起作用。 您还可以根据条件所基于的内容,在括号的内部和外部使用子