Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JAVA:如何使用流从列表中删除重复项_Java_List_Java Stream - Fatal编程技术网

JAVA:如何使用流从列表中删除重复项

JAVA:如何使用流从列表中删除重复项,java,list,java-stream,Java,List,Java Stream,我想根据列表中项目的属性(邮件)从列表中删除重复项。 我这样做: acteurs = acteurs.stream().distinct().collect(Collectors.toList()); Acteur的equals方法 @Override public boolean equals(Object o) { if (this.getMail().equals(((Acteur)o).getMail())) { return true; } i

我想根据列表中项目的属性(邮件)从列表中删除重复项。
我这样做:

acteurs = acteurs.stream().distinct().collect(Collectors.toList());
Acteur的equals方法

@Override
public boolean equals(Object o) {
    if (this.getMail().equals(((Acteur)o).getMail())) {
        return true;
    }
    if (this == o) {
        return true;
    }
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    Acteur acteur = (Acteur) o;
    if(acteur.id == null || id == null) {
        return false;
    }
    return Objects.equals(id, acteur.id);
}
在指令执行期间应调用equals方法

acteurs = acteurs.stream().distinct().collect(Collectors.toList());
但事实并非如此。
我错在哪里

更新:
我的解决方案:

List<Acteur> dto3s =acteurs.stream()
            .collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Acteur:: getMail))),
                ArrayList::new));
List dto3s=acturers.stream()
收集,收集收集,然后收集(
collector.toCollection(()->new TreeSet(Comparator.comparating(Acteur::getMail)),
ArrayList::new);

您违反了
等于
/
hashCode
合同


您需要根据需要实现
hashCode

您的equals方法似乎不正确,因为如果“if条件”未满足,您需要“return false”

您可以使用以下解决方案,其中您可以通过distinct键
mail
创建一个映射,并获取映射的值

acteurs.stream().collect(Collectors.toMap(a -> a.getMail(), Function.identity(), (a1, a2) -> a1)).values();
第三个arg
(a1,a2)->a1
意味着每当它得到一个冲突,即需要向映射添加一个具有相同键的条目
(键,值)
,它将使用映射的当前值,即无操作

请记住,这将仅通过
mail
属性进行比较,如果要使用映射逻辑通过更复杂的方式进行比较,可能需要正确实现
hash()
equals()


equals
方法无法编译。给我们看一个真实的。删除重复的acteur(具有相同的“邮件”值)的最佳方法是什么?此外,您的
equals
方法可以很容易地抛出
ClassCastException
@thomas您是否覆盖了
hashCode()
?他没有使用HasMap,所以hascode会出现在列表中吗@Talex您无法从这段代码中分辨出来。@AdityaRewari
HashMap
distinct
方法中在幕后使用。@AdityaRewari没有一个。
Stream#distinct()
操作当前使用基于散列的唯一强制集合实现。OP已更新问题。这一答案不再相关。