Raghave Shukla :
In Java 8, the docs for distinct() intermediate operation state
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
But it is not getting called
Equals method in my Item Class
@Override
public boolean equals(Object obj) {
System.out.println(this.name+"<->"+((Item)obj).name);
return this.name.equals(((Item)obj).name);
}
Defining Data in Data class
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;
}
Using Streams
Data.getItemList().stream().distinct().forEach(System.out::println)
but i realize that the equals method is not called
Benoit :
Beside equals()
, you need to override hashCode()
method as well. The distinct()
method probably uses a set internally, which in turn require a properly implemented hashCode()
. More info.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=310878&siteId=1