While working on a problem statement, I need to access the next Entry
of a Map
and based on a condition, I need to modify the next entry value.
I have been considering the solution provided here: How to get the previous key/value and the next key/value in Maps where I can access the higherEntry
using NavigableMap
but it throws:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractMap$SimpleImmutableEntry.setValue(AbstractMap.java:797)
which is totally understood. Here is the code snippet
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
}
}
How can I Iterate through a Map
, access and modify the next Entry when required?