java对象流定义,Java流不同是否不适用于自定义对象?

Javadocs say that distinct() - Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

I have a list of custom objects with some duplicates. When I run distinct() method on the streamed list, I still get the original list back. Why are the duplicates not getting removed even though I defined an equals method in the custom object ?

Code :

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 data = Arrays.asList(

new CustomType("a"),

new CustomType("b"),

new CustomType("a"),

new CustomType("c")

);

List filtered = data.stream().distinct().collect(Collectors.toList());

filtered.forEach(System.out::println);

}

}

Output :

[a]

[b]

[a]

[c]

BTW, I put a breakpoint in CustomType.equals(arg) and noticed that distinct( ) does not even call equals(arg).

解决方案

You always should override hashCode when overriding equals, else your equals method doesn't obey the expected contract:

@Override

public int hashCode() {

return data1.hashCode();

}

This works suggesting that distinct() first tests using hashCode and then if hashCodes are the same, uses the equals method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值