3 回答
TA贡献1826条经验 获得超6个赞
将 ArrayList 转换为 HashSet
这为 set.contains() 提供了 O(1)
使用 Map.equals() 检查 2 个映射是否具有相同的键值对(即检查内容是否相同)
现在您可以遍历一个集合并检查该元素是否存在于另一个集合中。这将为您提供线性时间而不是二次
TA贡献1841条经验 获得超3个赞
解决此问题的步骤:
将arrayList a1中的映射合并到映射lOld,将arrayList a2中的映射合并到映射lNew
从 lOld Map 和 lNew Map 中获取 keySet
将两个键集中的公共键添加到临时数组列表中
从两个 keySet 中删除这个临时 arrayList。
如果要以 arrayList 形式输出,请将 lOld 和 lNew 映射添加到新创建的 arrayLists
// start- get arrayList a1 index entries, fetch map,put all maps into one map to
//remove duplicate keys,doesn't matter value- because they will be removed anyways)
Map<String, String> lOld = new HashMap<String, String>();
for (i = 0; i < a1.size(); i++) {
HashMap<String, String> a1Map = a1.get(i);
lOld.putAll(a1Map);
}
//end
// start- get arrayList a2 index entries, fetch map,put all maps into other map to remove
// duplicate keys,doesn't matter value- because they will be removed anyways)
HashMap<String, String> lNew = new HashMap<String, String>();
for (j = 0; j < a2.size(); j++) {
HashMap<String, String> a2Map = a2.get(j);
lNew.putAll(a2Map);
}
//end
// check if first map keys (set) is in second map keys (set).
//if yes, add them into a list.
List<String> toRemove = new ArrayList<>();
Set<String> oldKeys = lOld.keySet();
Set<String> newKeys = lNew.keySet();
for (String oldKey : oldKeys) {
if (lNew.containsKey(oldKey)) {
toRemove.add(oldKey);
}
}
// remove that list elements from both sets which will remove them from map itself.
oldKeys.removeAll(toRemove);
newKeys.removeAll(toRemove);
// print both map
System.out.println("lold map is: " + lOld);
System.out.println("lNew map is: " + lNew);
// don't remove elements from set while iterating. it will give ConcurrentModificationException
TA贡献1831条经验 获得超4个赞
在集合中查找项目的最佳性能是使用 HashSet。
在这里查看: https ://www.baeldung.com/java-hashset-arraylist-contains-performance
添加回答
举报