Java流与众不同,无法在自定义对象上运行吗? [英] Java stream distinct does not work on custom objects?

查看:49
本文介绍了Java流与众不同,无法在自定义对象上运行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javadocs 说"distinct()-返回由该流的不同元素组成的流(根据Object.equals(Object)).

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

我有一些重复的自定义对象列表.当我在流式列表上运行distinct()方法时,仍然可以返回原始列表.即使我在自定义对象中定义了equals方法,为什么重复项也不会被删除?

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 ?

代码:

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(arg)中放置了一个断点,并注意到distinct()甚至没有调用equals(arg).

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

推荐答案

始终在覆盖等于时应覆盖hashCode,否则equals方法不遵守预期的合同:

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

这表明,distinct()首先使用hashCode进行测试,然后如果hashCodes相同,则使用equals方法.

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

这篇关于Java流与众不同,无法在自定义对象上运行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆