我有一个具有重复值的地图:
("A", "1");
("B", "2");
("C", "2");
("D", "3");
("E", "3");
我想地图有
("A", "1");
("B", "2");
("D", "3");
你知道如何摆脱重复值吗?
目前,我收到“java.util.ConcurrentModificationException”错误。
谢谢你。
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);
}
原文由 user2610852 发布,翻译遵循 CC BY-SA 4.0 许可协议
做一个反向的 HashMap!
现在您有了 hashMap,您需要反转它或打印它。
无论如何 不要 在迭代 hashMap 时删除。将值保存在列表中并在外循环中删除它们