【问题标题】:How to remove elements from a list based on the field values of objects in another list [closed]如何根据另一个列表中对象的字段值从列表中删除元素[关闭]
【发布时间】:2020-04-09 06:28:57
【问题描述】:

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

class Obj1
{
    private int id;
    private String x;
}

class Obj2
{
     private int id;
     private String y;
}

现在如何从List<Obj1> 中删除元素满足obj1.x==obj2.y 的对象

【问题讨论】:

  • 这个问题不清楚。身份证的目的是什么?此外,到目前为止,您尝试过什么?
  • 请澄清obj1.x==obj2.y。根据索引不清楚你是否需要这个。

标签: java arraylist collections java-stream


【解决方案1】:

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

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

然后你可以使用removeIf

list1.removeIf(obj1->ySet.contains(obj1.x));

【讨论】:

    【解决方案2】:
    obj2.forEach(per -> ids.add(per.getId()));
    
    List<Object> result = obj1.stream().filter(per -> ids.contains(per.getId())).collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2015-09-20
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 2019-10-24
      相关资源
      最近更新 更多