如何根据另一个列表中对象的字段值从列表中移除元素。

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

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&lt;String&gt; ySet = objs2.stream().map(Obj2::getY)
.collect(Collectors.toSet());

And then you can use removeIf

list1.removeIf(obj1-&gt;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 -&gt; ids.add(per.getId()));
		
List&lt;Object&gt; result = obj1.stream().filter(per -&gt; ids.contains(per.getId())).collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年4月9日 14:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/61115188.html
匿名

发表评论

匿名网友

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

确定