Java 8 distinct() does not invoke the equals method

Viewed 2162

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

2 Answers

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.

Are you also overriding the HashCode method??

There is no overloading possible for distinct. If you want to provide custom logic for comparison then you are better of using the distinctBy API.

DistinctBy

Related