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); }
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.
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.
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.
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.
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