【问题标题】:ArrayList removeAllArrayList removeAll
【发布时间】:2017-09-05 12:51:37
【问题描述】:

我有以下数组列表:

ArrayList<Obj o> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();

我想从 list1 中删除所有(字符串)ID 等于 list2 中的元素的元素。

if(o.getId().equals(one of the strings from list2)) -> remove.

如何使用 removeAll 或其他方式来做到这一点,而无需编写额外的 for。我正在寻找最好的方法来做到这一点。

提前谢谢你。

【问题讨论】:

  • 我认为即使 removeAll 在内部使用循环,所以我认为你不会比 for (Iterator it = list1.iterator(); it.hasNext(); ) { if (list2.contains(it.next().getId()) it.remove(); } 更好

标签: java arraylist


【解决方案1】:

如果你使用的是 java 8,你可以这样做:

ArrayList<YourClass> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();

list1.removeIf(item -> list2.contains(item.getId()));
// now list1 contains objects whose id is not in list2

假设YourClass 有一个返回StringgetId() 方法。


对于 java 7,使用 iterator 是可行的方法:

Iterator<YourClass> iterator = list1.iterator();
while (iterator.hasNext()) {
    if (list2.contains(iterator.next().getId())) {
        iterator.remove();
    }
}

【讨论】:

  • 非常感谢,这似乎是最好的方法,但我收到错误:-source 1.7 中不支持 lambda 表达式...
  • @Vluis 如果解决了,别忘了接受有帮助的答案!
猜你喜欢
  • 2021-12-16
  • 2015-05-01
  • 2016-03-16
  • 2014-09-28
  • 2016-03-06
  • 2016-06-27
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
相关资源
最近更新 更多