I have a list of objects List<A> list1
...
A
has two members id
and name
... Now I have one more list List<Integer> list2
containing only id's.
..I need to remove all the A
objects from list1
whose id is not present in list2
.
What I have tried so far:
void removeUnwanted(List<A> a, List<Integer> b) {
for (A object : a) {
if (!(b.contains(object.id))) {
b.remove(object)
}
}
}
Can anyone help me with suggestion most efficient way to do this ??
You should add the id's into a set for fast searching, then iterate over the list and remove the ids that are not in the id's set:
Set<Integer> ids = new HashSet<Integer>(list2);
Iterator<A> it = list1.iterator();
while (it.hasNext()) {
if (!ids.contains(it.next().id)) {
it.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