0
1

More than 1 year has passed since last update.

Stream#distinct

Posted at

distinct method 重複削除される
hashcode, equalsで判断されるためcustom classの場合は
overrideする
下記のサンプルはValue#equals()が常にtrueのために
同一値と判断され、すべて重複みなされる

class Value {

    String str;
    public Value(String str) {
        this.str = str;
    }

    @Override
    public int hashCode() {
        return 1;
    }

    @Override
    public boolean equals(Object obj) {
        return true;
    }

}
public class Outer {
    public static void main(String[] args) {
        List<Value> l = Arrays.asList(
                new Value("A"),
                new Value("B"),
                new Value("C"),
                new Value("A")
            );
        Stream<Value> s = l.stream();
        System.out.println(s.distinct().count());
    }
}
1
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1