tags:

views:

405

answers:

2

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;
 }
+3  A: 

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.

cletus
I'm trying to sort the String values according to a specific algorithm.
Rosarch
Then write a comparable interface and pass it to the constructor for the map. See http://java.sun.com/javase/6/docs/api/java/util/Comparator.html and http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html
Jherico
Actually, if you're trying to sort the string values then what you want is a Map<String, Integer>.
Jherico
A: 

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()));
    }
finnw