J'essaie de trouver un moyen optimal de trouver des éléments distincts dans 2 arraylistes qui contient une carte dedans.
ex. A1 et A2 sont des arraylistes où p>
La sortie attendue est la suivante: p>
Ma solution pour le problème est la suivante: p> existe une manière optimale de résoudre ce problème? p> Note: Carte à l'intérieur ArrayList contient plus d'une valeur. A1 et A2 sont juste pris pour un exemple. p> p>
3 Réponses :
Vous pouvez maintenant itérer plus d'un ensemble et vérifier si cet élément est présent dans l'autre ensemble. Cela vous donnera du temps linéaire au lieu de quadratique p>
Meilleures performances pour la recherche d'élément dans une collection utilise hashset. P>
Vérifiez ici: https://www.baeldung.com/java-hashst-arrayList-Contains- performance p>
Étapes pour résoudre ce problème:
// 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
Peut-être que cela aidera: Trouvez les éléments peu communs de deux ensembles