Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing objects from list based on Id match from other list

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 ??

like image 737
Alok Avatar asked Apr 04 '14 14:04

Alok


1 Answers

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();
    }
}
like image 57
tibtof Avatar answered Sep 28 '22 08:09

tibtof