Reputation: 167
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.
Upvotes: 4
Views: 1255
Reputation: 792
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();
}
}
Upvotes: 7