Suppose I have MutableMap<String, Integer>, and I want to sort on the Integer value.
What would be the recommended way to do that with this library? Is there a utility or method or recommended way of going about this with the Eclipse Collections library?
For example, suppose:
MutableMap<String, Integer> mutableMap = Maps.mutable.empty();
mutableMap.add(Tuples.pair("Three", 3));
mutableMap.add(Tuples.pair("One", 1));
mutableMap.add(Tuples.pair("Two", 2));
And I'd like to end up with a MutableMap<String, Integer> containing the same elements, but ordered/sorted so that the first element is ("One", 1), the second element ("Two", 2), and the third element ("Three", 3).
There is currently no direct API available in Eclipse Collections to sort a
Mapbased on its values.One alternative would be to flip the map into a
MutableSortedMapusingflipUniqueValues.This will give you a
MutableSortedMapthat is sorted on theIntegerkeys. The output here will be:{1=One, 2=Two, 3=Three}You could also store the
Pairsin aListfirst and then group them uniquely using theStringkey to create theMutableMap. If the values in theMapare thePairinstances, they can be used to create a sortedList,SortedSetorSortedBagusing direct APIs.Outputs:
All of the
toSortedmethods above operate on the values only. This is why I stored the values as thePairinstances.Note: I am a committer for Eclipse Collections.