我有两个列表
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);
然而,它可能并不比简单的迭代方法更有效,除非您使用 Set
而不是 List
。
关于java - 从列表中删除另一个列表中不存在的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30199359/