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 ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I'd put entries on the list and sort it. I don't recall any map that can be ordered by values, only by keys. You could use BiMap from Guava, but it requires values uniqueness.
Example:
Simple method to get an immutable copy of your map sorted by descending value. Remove the call to
reverse()
if you want ascending order. Requires Google Guava.I would do this with Guava as follows:
With guava, there is even cleaner way than @LoisWasserman's anwer - using Ordering combined with
Functions.forMap
:or if values aren't
Comparable
:An example (with first option - natural ordering):
outputs:
(I use ImmutableSortedMap here, but TreeMap can also be used if mutability is required.)
EDIT:
If there are identical values (more exactly if there are two values for which
Comparator.compare(String v1, String v2)
returns 0) ImmutableSortedMap throws an exception. Ordering must not return, so i.e. you should order map by values first and keys next if both values are equal (keys aren't supposed to be equal) by usingOrdering.compound
:prints:
I think the
DualTreeBidiMap
of Apache Commons Collections should make this possible, probably by iterating over the return frominverseBidiMap()
.But I don't think this allows for duplicate values - as the name says, the structure is simply based on keeping two trees, which is really the only thing that makes sense, since values in a map have no meaning to the map structure.
I think you have to roll your own implementation of such a map. Fortunately, it shouldn't be much of an issue with Guava:
Fail-fast iterators are not present in this implementation; please add them for yourself if required. Please also note that setting a value via Map.Entry.setValue would cause havoc with the sort order, which is why I used
unmodifyableMap
in entry set.