Java8流-删除流不同的重复项 [英] Java8 Streams - Remove Duplicates With Stream Distinct

查看:94
本文介绍了Java8流-删除流不同的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个流,例如:

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.

我正在尝试了解 distinct() 方法有效.我在文档中读到它基于对象的等于"方法.但是,当我尝试包装String时,我注意到equals方法从不被调用,并且什么也没有删除.这里有我想念的东西吗?

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?

包装类:

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

和一些简单的代码:

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

推荐答案

每当您覆盖equals时,您还需要覆盖hashCode()方法,该方法将在distinct()的实现中使用.

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

...就可以了.

这篇关于Java8流-删除流不同的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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