Question

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;
    }
Was it helpful?

Solution

Well, if you're just after a Map where the keys are ordered, use a SortedMap instead.

SortedMap<Integer, String> map = new TreeMap<Integer, String>();

You can rely on the natural ordering of the key (as in, its Comparable interface) or you can do custom ordering by passing a Comparator.

Alternatively you can call setValue() on the Entry.

Map.Entry<Integer, String> prev = null;
for (Map.Entry<Integer, String> entry: collection.entrySet()) {
  if (prev != null) {
    if (entry.isBefore(prev)) {
      String current = entry.getValue();
      entry.setValue(prev.getValue();
      prev.setValue(current);
    }
  }
  prev = entry;
}

Personally I'd just go with a SortedMap.

OTHER TIPS

There's nothing like that in the Map or Entry interfaces but it's quite simple to implement:

    Map.Entry<Integer, String> prev = null;
    for (Map.Entry<Integer, String> entry: collection.entrySet()) {
            if (prev != null) {
                    if (entry.isBefore(prev)) {
                            swapValues(e, prev);
                    }
            }
            prev = entry;
    }

    private static <V> void swapValues(Map.Entry<?, V> first, Map.Entry<?, V> second)
    {
            first.setValue(second.setValue(first.getValue()));
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top