英文:
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;
}
我想基于 schoolName
和 location
从世界对象列表中移除学校对象列表。由于在这两个字段上使用 equals
和 hashCode
方法会产生其他问题,所以请帮我使用流(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 -> schoolList.stream()
.anyMatch(school -> world.getSchoolName().equals(school.getSchoolName())
&& world.getLocation().equals(school.getLocation())
)
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论