ho una mappa con i valori duplicati:Rimuovere i valori duplicati di HashMap in Java
("A", "1");
("B", "2");
("C", "2");
("D", "3");
("E", "3");
Vorrei la mappa di avere
("A", "1");
("B", "2");
("D", "3");
Sapete come sbarazzarsi del duplicato valori?
Al momento, viene visualizzato l'errore 'java.util.ConcurrentModificationException'.
Grazie.
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
Set<String> keys = map.keySet(); // The set of keys in the map.
Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = map.get(key);
System.out.println(key + "\t" + value);
String nextValue = map.get(key);
if (value.equals(nextValue)) {
map.remove(key);
}
}
System.out.println(map);
}
Perché mantieni il 'B' e tralasciamo' C'? Ricorda, 'HashMap' non mantiene l'ordine degli elementi inseriti. –
Puoi dire esattamente il requisito? Sembra che tu voglia valori unici. HashMap può darti chiavi uniche. Invertendo la chiave e il valore sarà sufficiente per te? – midhunhk
@RohitJain +1 Questa è la domanda! – NINCOMPOOP