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}]
我想从list1中删除另一个list2中不存在的所有对象2我的预期输出是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?
我可以通过list1迭代,并可以检查元素是否存在然后什么都不做删除元素。但我想知道有更好的方法还是更简单的代码?
1 个解决方案
#1
The Collection.retainAll
method exists for exactly that purpose:
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.
仅保留此集合中包含在指定集合中的元素。换句话说,从此集合中删除未包含在指定集合中的所有元素。
Usage would be:
用法是:
list1.retainAll(list2);
It might not be any more efficient than a naive iteration approach, however, unless you use Set
s instead of List
s.
然而,它可能不比天真的迭代方法更有效,除非您使用集而不是列表。
#1
The Collection.retainAll
method exists for exactly that purpose:
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.
仅保留此集合中包含在指定集合中的元素。换句话说,从此集合中删除未包含在指定集合中的所有元素。
Usage would be:
用法是:
list1.retainAll(list2);
It might not be any more efficient than a naive iteration approach, however, unless you use Set
s instead of List
s.
然而,它可能不比天真的迭代方法更有效,除非您使用集而不是列表。