我正在尝试替换 LinkedHashMap 中的整个键/值对,但似乎不起作用。我收到并发修改异常。 有没有一种方法可以在不进行任何重大更改的情况下替换同一位置的键的整个键/值对。
我尝试执行以下操作:
Map<String, String> testMap = new LinkedHashMap<String, String>();
testMap.put("1", "One");
testMap.put("2", "Two");
testMap.put("3", "Three");
testMap.put("4", "Four");
testMap.put("5", "Five");
testMap.put("6", "Six");
/*
* Removing an element from the Map.
*/
Iterator<Entry<String, String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
System.out.print(entry.getKey() + "->" + entry.getValue() + "; ");
if (entry.getKey().equals("1"))
iter.remove(); // remove one entry (key/value) with key "1". Ok
if (entry.getValue().equalsIgnoreCase("Two"))
iter.remove(); // removing all entries (key/value) for value "Two". Ok
if (entry.getKey().equals("3"))
entry.setValue("Updated_Three"); // Updating value for key 3. Ok
// Below how to now add a new key/value pair in my testMap at this position
// without affecting any other order?
if (entry.getKey().equals("4")) {
iter.remove();
// How to now add a new key/value pair at this position without affecting any
// other order.
// testMap.put("44", "FourFour"); // Removing entry with key 4 and adding a new
// key/valuepair to hashmap. It throws ConcurrentModificationException. Any
// other way to perform this?
}
}
最佳答案
据我了解,您想坚持使用 LinkedHashMap。如果您在迭代时尝试添加新数据(更改 LinkedHashMap 的结构),您将收到 ConcurrentModificationException。
下面的代码可能会满足您的要求:
public static void main(String args[]) throws IOException {
Map<String, String> testMap = new LinkedHashMap<>();
testMap.put("1", "One");
testMap.put("2", "Two");
testMap.put("3", "Three");
testMap.put("4", "Four");
int indexOfFourtyFour = -1;
System.out.println("Test Map before :: " + testMap);
Iterator<Entry<String, String>> itr = testMap.entrySet().iterator();
int index = 0;
while (itr.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) itr.next();
if (entry.getKey().equals("3")) {
itr.remove();
indexOfFourtyFour = index;
}
index ++;
}
if (indexOfFourtyFour > -1) {
add(testMap, indexOfFourtyFour, "44", "FourFour");
}
System.out.println("Test Map after :: " + testMap);
}
public static <K, V> void add(Map<K, V> map, int index, K key, V value) {
assert (map != null);
assert !map.containsKey(key);
assert (index >= 0) && (index < map.size());
int i = 0;
List<Entry<K, V>> rest = new ArrayList<Entry<K, V>>();
for (Entry<K, V> entry : map.entrySet()) {
if (i++ >= index) {
rest.add(entry);
}
}
map.put(key, value);
for (int j = 0; j < rest.size(); j++) {
Entry<K, V> entry = rest.get(j);
map.remove(entry.getKey());
map.put(entry.getKey(), entry.getValue());
}
}
输出:
Test Map before :: {1=One, 2=Two, 3=Three, 4=Four}
Test Map after :: {1=One, 2=Two, 44=FourFour, 4=Four}
在 LinkedHashMap 中的特定索引处添加元素的代码 来自HERE
关于java - 如何在同一替换位置替换 LinkedHashmap 中的整个键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936835/