Can I swap the keys of two values of a Hashmap, or do I need to do something clever?
Something that would look something like this:
Map.Entry<Integer, String> prev = null;
for (Map.Entry<Integer, String> entry: collection.entrySet()) {
if (prev != null) {
if (entry.isBefore(prev)) {
entry.swapWith(prev)
}
}
prev = entry;
}
There's nothing like that in the
Map
orEntry
interfaces but it's quite simple to implement:Well, if you're just after a Map where the keys are ordered, use a
SortedMap
instead.You can rely on the natural ordering of the key (as in, its
Comparable
interface) or you can do custom ordering by passing aComparator
.Alternatively you can call
setValue()
on theEntry
.Personally I'd just go with a
SortedMap
.