Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
344 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...