我有以下排列清单:
ArrayList<Obj o> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();我希望从list1中删除所有具有(string)ID的元素,该ID等于list2中的元素。
if(o.getId().equals(one of the strings from list2)) -> remove.我如何使用removeAll或其他方式做到这一点,而不必编写额外的for。我在寻找最理想的方法来做到这一点。
提前谢谢你。
发布于 2017-09-05 12:58:10
如果您使用的是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有一个返回String的getId()方法。
对于java 7,使用iterator是可行的方法:
Iterator<YourClass> iterator = list1.iterator();
while (iterator.hasNext()) {
if (list2.contains(iterator.next().getId())) {
iterator.remove();
}
}https://stackoverflow.com/questions/46055463
复制相似问题