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
The distinct () method returns a new stream consisting of the distinct elements from the given stream. For checking the equality of the stream elements, the equals () method is used. The distinct () method guarantees the ordering for the streams backed by an ordered collection.
Method 1 (Using Stream API’s distinct () Method): For Java 8, You can use Java 8 Stream API. To get distinct values, the distinct () method is an intermediate operation that also filters the stream to pass the next operation. Java Stream collect () is used to collect the stream elements to a collection (in this case a list).
Java Stream distinct () 1 Stream distinct () Method#N#The distict () method is one of the stateful intermediate operation which uses the state... 2 Stream distinct () Examples More ...
ANGULAR ANDROID Home > Java 8 Java 8 Distinct Example By Arvind Rai, September 04, 2017 On this page we will provide Java 8 Stream distinct()example. distinct()returns a stream consisting of distinct elements of that stream. distinct()is the method of Streaminterface. distinct()uses hashCode()and equals()methods to get distinct elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With