英文:
How to remove elements from a list based on the field values of objects in another list
问题
我有两个对象列表。List<Obj1> 和 List<Obj2>
。
class Obj1
{
private int id;
private String x;
}
class Obj2
{
private int id;
private String y;
}
现在我该如何从 List<Obj1>
中移除那些满足条件 obj1.x==obj2.y
的对象?
英文:
I have two lists of objects. List<Obj1> and List<Obj2>
.
class Obj1
{
private int id;
private String x;
}
class Obj2
{
private int id;
private String y;
}
Now how can I remove the objects from List<Obj1>
whose elements satisfy obj1.x==obj2.y
答案1
得分: 1
最佳方法是将第二个列表对象 obj2
的属性 y
收集到 Set
中:
Set<String> ySet = objs2.stream().map(Obj2::getY)
.collect(Collectors.toSet());
然后您可以使用 removeIf
:
list1.removeIf(obj1 -> ySet.contains(obj1.x));
英文:
The best way would be collecting second list object obj2
property y
into Set
Set<String> ySet = objs2.stream().map(Obj2::getY)
.collect(Collectors.toSet());
And then you can use removeIf
list1.removeIf(obj1->ySet.contains(obj1.x));
答案2
得分: -1
obj2.forEach(per -> ids.add(per.getId()));
List<Object> result = obj1.stream().filter(per -> ids.contains(per.getId())).collect(Collectors.toList());
英文:
obj2.forEach(per -> ids.add(per.getId()));
List<Object> result = obj1.stream().filter(per -> ids.contains(per.getId())).collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论