アルマーニ:
Javadocは、このストリームの別個の要素からなるストリーム(はObject.equalsに従って(オブジェクト))を返し-異なるが()と言います。
私はいくつかの重複したカスタムオブジェクトのリストを持っています。私は実行するとdistinct()
、ストリーミングリストに方法を、私はまだ元のリストの背中を取得します。なぜ重複は、私はカスタムオブジェクトにequalsメソッドを定義していても削除取得されていませんか?
コード:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class CustomType {
private String data1;
public CustomType(String data1) { this.data1 = data1; }
public String getData1() { return data1; }
@Override
public boolean equals(Object other){
CustomType otherC = (CustomType) other;
return this.getData1().equals(otherC.getData1());
}
@Override
public String toString(){
return "[" + data1 + "]";
}
}
public class StreamDistinctTest {
public static void main(String [] args){
List<CustomType> data = Arrays.asList(
new CustomType("a"),
new CustomType("b"),
new CustomType("a"),
new CustomType("c")
);
List<CustomType> filtered = data.stream().distinct().collect(Collectors.toList());
filtered.forEach(System.out::println);
}
}
出力:
[a]
[b]
[a]
[c]
ところで、私はCustomType.equalsにブレークポイントを置く(引数)と)(個別の偶数(引数)等号を呼び出していないことに気づきました。
ウナギのホバークラフトのフル:
あなたは常に等号をオーバーライドするときのhashCodeをオーバーライドする必要があり、そうでないあなたのequalsメソッドは、予想される契約に従いません。
@Override
public int hashCode() {
return data1.hashCode();
}
これは、別個の()最初の試験はハッシュコードを使用してハッシュコードが同じである場合、次に、方法を等しく使用することを示唆している働きます。