从列表中删除另一个列表中不存在的所有对象

Remove all objects from list that does not exist in another 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);

我想从 list1 中删除另一个 list2 中不存在的所有对象
我的预期输出是 list1 -- [{2=2, 1=1}]

我可以遍历 list1 并检查元素是否存在,然后什么都不做,删除元素。但我想知道是否有更好的方法或更简单的代码?

Collection.retainAll 方法就是为了这个目的而存在的:

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.

用法为:

list1.retainAll(list2);

它可能不会比简单的迭代方法更有效,但是,除非您使用 Sets 而不是 Lists。