![](/img/trans.png)
[英]How to remove an item from ArrayList<HashMap<String, Object>>
[英]How to remove the dulpicates from ArrayList<HashMap<String,Object>> in java?
我有一个HashMap类型的Arraylist。 我需要消除相同的重复条目。 我正在使用该套件删除重复项,如下所示。
Set<Object> valueSet = new HashSet<Object>();
for(HashMap<String, Object> map: mDataList){
valueSet.addAll(map.values());
}
但是在集合中,我们无法存储HashMap。 我希望将具有键,值对的HashMap作为返回值,并将其添加到列表中。 那就是最终值应采用ArrayList>的格式。
您能在这方面帮助我吗? 谢谢。
Set应该能够包含一个HashMap。
我假设这里的重复意味着2个HashMap之间的键,值对相同。 在这种情况下,您可以尝试
Set<HashMap<String, Object>> abc = new HashSet<HashMap<String, Object>>();
HashMap<String, Object> a1 = new HashMap<String, Object>();
a1.put("a", "a");
HashMap<String, Object> a2 = new HashMap<String, Object>();
a2.put("a", "a");
HashMap<String, Object> a3 = new HashMap<String, Object>();
a3.put("c", "c");
abc.add(a1);
abc.add(a2);
abc.add(a3);
for (HashMap<String, Object> each : abc){
System.out.println(each.toString()); //{a=a}, {c=c}
}
根据您的评论进行编辑
您可以将值反转为新HashMap的键。 查看下面的代码
String yourkey = "key";
List<HashMap<String, Object>> oldList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> a1 = new HashMap<String, Object>();
a1.put(yourkey, "1");
HashMap<String, Object> a2 = new HashMap<String, Object>();
a2.put(yourkey, "1");
HashMap<String, Object> a3 = new HashMap<String, Object>();
a3.put(yourkey, "2");
oldList.add(a1);
oldList.add(a2);
oldList.add(a3);
HashMap<Object, Object> newMap = new HashMap<Object, Object>();
for (HashMap<String, Object> each : oldList){
// Put the value as key. Duplicate will be overridden
newMap.put( each.get(yourkey), each);
}
List<HashMap<String, Object>> noDuplicateList = new ArrayList<HashMap<String, Object>>();
for (Object each : newMap.keySet()) {
noDuplicateList.add( (HashMap)newMap.get(each) );
}
System.out.println(noDuplicateList); // [{key=2}, {key=1}]
您必须确保“值”具有可比性(此处使用字符串)。 否则,请创建自己的equals方法。
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.