gpt4 book ai didi

Java 8 distinct() 不调用 equals 方法

转载 作者:行者123 更新时间:2023-11-29 09:58:37 24 4
gpt4 key购买 nike

在 Java 8 中,distinct() 中间操作状态的文档

Returns a stream consisting of the distinct elements (according to >Object.equals(Object)) of this stream. For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first

但它没有被调用

我的 Item 类中的 Equals 方法

@Override
public boolean equals(Object obj) {
System.out.println(this.name+"<->"+((Item)obj).name);
return this.name.equals(((Item)obj).name);
}

在数据类中定义数据

public static List<Item> getItemList(){     
itemData.add(new Item("Orange","Citrus Fruit","Orange",30,true,false));
itemData.add(new Item("Apple Green","Universal Fruit","Green",60,false,true));
itemData.add(new Item("Papaya","Wonderful Fruit","Yellow",120,false,true));
itemData.add(new Item("Papaya","Wonderful Fruit","Green",100,false,true));
.
.
.
itemData.add(new Item("Strawberry","Citrus Fruit","Red",25,true,false));
itemData.add(new Item("Sapota","Brown Fruit","Brown",32,false,true));

return itemData;
}

使用流

Data.getItemList().stream().distinct().forEach(System.out::println)

但是我意识到没有调用equals方法

最佳答案

除了equals(),你还需要覆盖hashCode()方法。 distinct() 方法可能在内部使用了一个集合,这又需要一个正确实现的 hashCode()。更多 info .

关于Java 8 distinct() 不调用 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56650863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com