Java 8从一个List中移除另一个List

huangapple go评论81阅读模式
英文:

Java 8 Remove 1 List from Other

问题

我有两个不同对象的列表

```java
class School {
    private String schoolName;
    private String location;
    private String pinCode;
    private String rating;
}

class World {
    private String schoolName;
    private String location;
    private String country;
    private String region;
}

我想基于 schoolNamelocation 从世界对象列表中移除学校对象列表。由于在这两个字段上使用 equalshashCode 方法会产生其他问题,所以请帮我使用流(Streams)来实现这个功能。


<details>
<summary>英文:</summary>

I have two list of different Objects.

class School {
private String schoolName;
private String location;
private String pinCode;
private String rating;
}

class World {
private String schoolName;
private String location;
private String country;
private String region;
}


I want to remove the list of School objects from List of World objects based on `schoolName` and `location`. I cannot use `equals` and `hashCode` methods on those two fields as it is creating some other problem. Please help me how it can be done using streams.


</details>


# 答案1
**得分**: 1

你可以使用 `filter`:

```java
worldList.stream()
    .filter(world -> schoolList.stream()
        .anyMatch(school -> world.getSchoolName().equals(school.getSchoolName())
                         && world.getLocation().equals(school.getLocation())
    ))
    .collect(Collectors.toList());
英文:

You can use filter:

worldList.stream()
    .filter(world -&gt; schoolList.stream()
        .anyMatch(school -&gt; world.getSchoolName().equals(school.getSchoolName())
                         &amp;&amp; world.getLocation().equals(school.getLocation())
    )
    .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年6月29日 17:57:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/62635637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定