开发者

Iterating through HashMap by values

I need to loop through a HashMap, but to give importance to the values' order. For example, consider the following hash map of <String, Integer>:

{"dog" : 2, "bird": 3, "cat" : 1}
开发者_运维知识库

Now, I need to loop through the hasp map in order of ascending values, so that

for () {
 System.out.println( currentKey );
}

will always output

"cat", "dog", "bird"


Maybe this will help:

Sort a Map<Key, Value> by values (Java)


Well, you may be interested in instead using a TreeMap, which sorts your entries by key.

Otherwise, you may be interested looking into Map.keySet(), Map.entrySet(), or Map.values().

If you still want to keep your Map a HashMap, you could use one of Collections' numerous functions for getting sorted collections (e.g. you could get a sorted version of your map, sort a list, etc).


Since I see you specifically want to sort by values, I think Michał Minicki's answer ought to be what you want.


If you want to have the map sort itself by value as you insert entries then the easiest way would probably be to use something like the TreeMultimap in Google's collections library.

If you still want to use a hashmap but have the values sorted when you retrieve them from the set, then you can take two approaches - either you can get the values using the values() method and then run Collections.sort() on the returned list, or you can again use a class like TreeMultimap, adding all the entries in the current hashmap and then enumerating through them.


Another example using Guava:

Pros:

  • Returns entries (not just keys)
  • Does not require the keys to be Comparable

static <K, V>Set<Map.Entry<V, K>>
entriesByValue(Map<K, V> source, Comparator<V> cmp) {
    SortedMap<V, Collection<K>> inverseMap = Maps.newTreeMap(cmp);
    Supplier<Set<K>> setFactory = new Supplier<Set<K>>() {
        public Set<K> get() {
            return Sets.newHashSet();
        }
    };
    SetMultimap<V, K> inverseMM =
        Multimaps.newSetMultimap(inverseMap, setFactory);
    Multimaps.invertFrom(Multimaps.forMap(source), inverseMM);
    return Collections.unmodifiableSet(inverseMM.entries());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜