Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all objects from list that does not exist in another list

I have two list

    List<Map<String,Object>> list1 =  new ArrayList<Map<String,Object>>();
    List<Map<String,Object>> list2 =  new ArrayList<Map<String,Object>>();

    HashMap<String, Object> hm = new HashMap<String, Object>();
    hm.put("1", new Long(1L));
    HashMap<String, Object> hm2 = new HashMap<String, Object>();
    hm2.put("2", new Long(2L));
    HashMap<String, Object> hm3 = new HashMap<String, Object>();
    hm3.put("3", new Long(3L));
    HashMap<String, Object> hm4 = new HashMap<String, Object>();
    hm4.put("4", new Long(4L));

    list1.add(hm);
    list1.add(hm2);
    list1.add(hm3);
    list1.add(hm4);

    HashMap<String, Object> hm1 = new HashMap<String, Object>();
    hm1.put("1", new Long(1L));
    HashMap<String, Object> hm5 = new HashMap<String, Object>();
    hm5.put("2", new Long(2L));

    list2.add(hm1);
    list2.add(hm5);

I want to remove all objects from list1 that does not exist in another list2
My expected output is list1 -- [{2=2, 1=1}]

I can Iterate through list1 and can check if element present then do nothing else remove the element. But I want to know is there a better approach or simpler code?

like image 619
Amar Avatar asked May 12 '15 19:05

Amar


1 Answers

The Collection.retainAll method exists for exactly that purpose:

Retains only the elements in this collection that are contained in the specified collection. In other words, removes from this collection all of its elements that are not contained in the specified collection.

Usage would be:

list1.retainAll(list2);

It might not be any more efficient than a naive iteration approach, however, unless you use Sets instead of Lists.

like image 97
Boann Avatar answered Sep 22 '22 04:09

Boann