ArrayList removeAll

I have the following arraylists:

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

I want to remove all elements from list1 that have a (string) ID that is equal to elements from list2.

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

How can I do this using removeAll or some other way without having to write extra for. I am looking for the most optimal way to do this.

Thanks in advance.

+4
source share
1 answer

If you are using java 8, you can do:

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

Assuming it YourClasshas a method getId()that returns String.


For java 7 use iteratoris the way to go:

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

Source: https://habr.com/ru/post/1685087/


All Articles