Search code examples
javacollectionsdictionaryguavaapache-commons

Map that could be iterated in the order of values


I need a Map that could be iterated in the decreasing order of its values. Does any of the standard libraries like Apache Commons or Guava provide this kind of map ?


Solution

  • I would do this with Guava as follows:

    Ordering<Map.Entry<Key, Value>> entryOrdering = Ordering.from(valueComparator)
      .onResultOf(new Function<Entry<Key, Value>, Value>() {
        public Value apply(Entry<Key, Value> entry) {
          return entry.getValue();
        }
      }).reverse();
    // Desired entries in desired order.  Put them in an ImmutableMap in this order.
    ImmutableMap.Builder<Key, Value> builder = ImmutableMap.builder();
    for (Entry<Key, Value> entry : 
        entryOrdering.sortedCopy(map.entrySet())) {
      builder.put(entry.getKey(), entry.getValue());
    }
    return builder.build();
    // ImmutableMap iterates over the entries in the desired order