Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Streams - Remove Duplicates With Stream Distinct

I have a stream such as:

Arrays.stream(new String[]{"matt", "jason", "michael"}); 

I would like to remove names that begin with the same letter so that only one name (doesn't matter which) beginning with that letter is left.

I'm trying to understand how the distinct() method works. I read in the documentation that it's based on the "equals" method of an object. However, when I try wrapping the String, I notice that the equals method is never called and nothing is removed. Is there something I'm missing here?

Wrapper Class:

static class Wrp {     String test;     Wrp(String s){         this.test = s;     }     @Override     public boolean equals(Object other){         return this.test.charAt(0) == ((Wrp) other).test.charAt(0);     } } 

And some simple code:

public static void main(String[] args) {     Arrays.stream(new String[]{"matt", "jason", "michael"})     .map(Wrp::new)     .distinct()     .map(wrp -> wrp.test)     .forEach(System.out::println); } 
like image 431
Matt Klooster Avatar asked Jan 12 '15 21:01

Matt Klooster


People also ask

How does distinct work in streams?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.

How u will remove duplicates in an stream of integers?

Remove duplicates from infinite integers The stream of integers is unsorted and are provided by iterator so that you don't have the access to all the elements at once. You have to return another iterator from the input iterator so that there are no duplicates and the input order is maintained.

Does Java stream distinct preserve order?

Java Stream distinct() MethodIf the stream is ordered, the encounter order is preserved. It means that the element occurring first will be present in the distinct elements stream. If the stream is unordered, then the resulting stream elements can be in any order.


1 Answers

Whenever you override equals, you also need to override the hashCode() method, which will be used in the implementation of distinct().

In this case, you could just use

@Override public int hashCode() {    return test.charAt(0); } 

...which would work just fine.

like image 177
Louis Wasserman Avatar answered Oct 05 '22 22:10

Louis Wasserman