【发布时间】:2019-07-08 02:01:33
【问题描述】:
在处理问题陈述时,我需要访问 Map 的下一个 Entry 并根据条件修改下一个条目值。
我一直在考虑这里提供的解决方案:How to get the previous key/value and the next key/value in Maps 我可以使用NavigableMap 访问higherEntry,但它会抛出:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractMap$SimpleImmutableEntry.setValue(AbstractMap.java:797)
这是完全可以理解的。这是代码sn-p
for (Map.Entry<Character, Integer> current : myMap.entrySet()) {
Map.Entry<Character, Integer> next = myMap.higherEntry(current.getKey());
if (current.getValue() == next.getValue()) {
// Code block
} else if (current.getValue() > next.getValue()) {
// Code block
} else {
next.setValue(1); // Line that throws Exception
}
}
如何遍历Map,在需要时访问和修改下一个条目?
【问题讨论】:
-
为什么不直接遍历键列表,然后使用键检索值进行比较,然后使用
Map.put()覆盖它?您正在使用的Map的实现对条目使用SimpleImmutableEntry实现,这不允许您使用setValue()。
标签: java dictionary collections