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

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

How to remove elements from a list based on the field values of objects in another list

问题

我有两个对象列表。List<Obj1> 和 List<Obj2>

  1. class Obj1
  2. {
  3. private int id;
  4. private String x;
  5. }
  6. class Obj2
  7. {
  8. private int id;
  9. private String y;
  10. }

现在我该如何从 List<Obj1> 中移除那些满足条件 obj1.x==obj2.y 的对象?

英文:

I have two lists of objects. List<Obj1> and List<Obj2>.

  1. class Obj1
  2. {
  3. private int id;
  4. private String x;
  5. }
  6. class Obj2
  7. {
  8. private int id;
  9. private String y;
  10. }

Now how can I remove the objects from List<Obj1> whose elements satisfy obj1.x==obj2.y

答案1

得分: 1

最佳方法是将第二个列表对象 obj2 的属性 y 收集到 Set 中:

  1. Set<String> ySet = objs2.stream().map(Obj2::getY)
  2. .collect(Collectors.toSet());

然后您可以使用 removeIf

  1. list1.removeIf(obj1 -> ySet.contains(obj1.x));
英文:

The best way would be collecting second list object obj2 property y into Set

  1. Set&lt;String&gt; ySet = objs2.stream().map(Obj2::getY)
  2. .collect(Collectors.toSet());

And then you can use removeIf

  1. list1.removeIf(obj1-&gt;ySet.contains(obj1.x));

答案2

得分: -1

  1. obj2.forEach(per -> ids.add(per.getId()));
  2. List<Object> result = obj1.stream().filter(per -> ids.contains(per.getId())).collect(Collectors.toList());
英文:
  1. obj2.forEach(per -&gt; ids.add(per.getId()));
  2. 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:

确定