使用Java 8在列表中查找其他列表中不存在的元素 [英] Find elements in a list that are not present in another list using java 8

查看:1029
本文介绍了使用Java 8在列表中查找其他列表中不存在的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个列表.要求是根据条件过滤掉list1中不在list2中的元素.

I have 2 lists. The requirement is to filter out elements in list1 that are not in list2 based on condition.

  Class Fighter
  {
    String name;
    String address;
  }     
  List<Fighter> pairs1 = new ArrayList();
    pairs1.add(new Fighter("a", "a"));
    pairs1.add(new Fighter("b", "a"));

    List<Fighter> pairs2 = new ArrayList();
    pairs2.add(new Fighter("a", "c"));
    pairs2.add(new Fighter("a", "d"));
    Set<Fighter> finalValues = new HashSet<>();


    finalValues = pairs1.stream().filter(firstList -> 
   pairs2.stream().noneMatch(secondList -> 
   firstList.getName().equals(secondList.getName())
            && firstList.getName().equals(secondList.getName()))).collect(Collectors.toSet());

    System.out.println(finalValues);

预期输出:a = a,b = a

Expected Output : a=a, b=a

说明:list1中不在list2中的元素

Explanation: Elements in list1 that are not in list2

上面的代码没有给出预期的输出.请让我知道如何纠正上述流代码以获取输出

The above code is not giving the expected output. Please let me know how the above stream code can be corrected to get the output

推荐答案

首先覆盖Fighter类中的equals和hashcode方法.

First override the equals and hashcode methods in Fighter class.

@Override
public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof Fighter))
        return false;
    Fighter f = (Fighter) o;
    return f.name.equals(name) && f.address.equals(address);
}

@Override
public int hashCode() {
    int result = name.hashCode();
    result = 31 * result + address.hashCode();
    return result;
}

然后根据pairs2创建一个Set.最后使用它的contains方法来获取设置差异.这是它的样子,

Then create a Set from pairs2. Finally use it's contains method to get the set difference. Here's how it looks,

Set<Fighter> pairs2Set = new HashSet<>(pairs2);
Set<Fighter> setDiff = pairs1.stream()
    .filter(f -> !pairs2Set.contains(f))
    .collect(Collectors.toSet());

这篇关于使用Java 8在列表中查找其他列表中不存在的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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