Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList removeAll

Tags:

java

arraylist

I have the following arraylists:

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

I want to remove all of the elements from list1 that have (string)ID that equals the elements from list2.

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

How can I do that with removeAll or some other way without having to write an additional for. I'm searching for the most optimal way to do this.

Thank you in advance.

like image 556
Vluiz Avatar asked Mar 09 '23 04:03

Vluiz


1 Answers

If you are using java 8, you could 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 YourClass has a getId() method that returns a String.


For java 7, using iterator is the way to go:

Iterator<YourClass> iterator = list1.iterator();
while (iterator.hasNext()) {
    if (list2.contains(iterator.next().getId())) {
        iterator.remove();
    }
}
like image 107
Jonathan Avatar answered Mar 20 '23 05:03

Jonathan