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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With