我正在尝试寻找一种最佳方法,以便在其中包含映射的2个arrayLists中找到不同的元素。
例如a1和a2是其中的数组列表
预期输出为:
我对这个问题的解决方案是:
List<Map<String, String>> lOld = new ArrayList<Map<String,String>>();
for (int i = 0; i < a2.size(); i++) {
boolean found = false;
for (int j = 0; j < a1.size(); j++) {
if(a2.get(i).get("val").equals(a1.get(j).get("val"))){
found = true;
break;
}
}
if(found == false){
lOld.add(a2.get(i));
}
}
List<Map<String, String>> lNew = new ArrayList<Map<String,String>>();
for (int i = 0; i < a1.size(); i++) {
boolean found = false;
for (int j = 0; j < a2.size(); j++) {
if(a1.get(i).get("val").equals(a2.get(j).get("val"))){
found = true;
break;
}
}
if(found == false){
lNew.add(a1.get(i));
}
}
是否有解决此问题的最佳方法?
注意:arrayList内部的映射包含一个以上的值。仅以a1和a2为例。
答案 0 :(得分:0)
现在,您可以遍历一个集合并检查该元素是否存在于另一个集合中。这将为您提供线性时间,而不是二次方
答案 1 :(得分:0)
解决此问题的步骤:
// 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
答案 2 :(得分:-1)
在HashSet中查找集合中项目的最佳性能。
在这里查看: https://www.baeldung.com/java-hashset-arraylist-contains-performance