rs99483
rs99483

Reputation: 75

Using the Eclipse Collections library, how do I sort MutableMap on the value?

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).

Upvotes: 2

Views: 792

Answers (1)

Donald Raab
Donald Raab

Reputation: 6706

There is currently no direct API available in Eclipse Collections to sort a Map based on its values.

One alternative would be to flip the map into a MutableSortedMap using flipUniqueValues.

MutableSortedMap<Integer, String> sortedMap = SortedMaps.mutable.empty();
sortedMap.putAll(mutableMap.flipUniqueValues());

System.out.println(sortedMap);

This will give you a MutableSortedMap that is sorted on the Integer keys. The output here will be: {1=One, 2=Two, 3=Three}

You could also store the Pairs in a List first and then group them uniquely using the String key to create the MutableMap. If the values in the Map are the Pair instances, they can be used to create a sorted List, SortedSet or SortedBag using direct APIs.

MutableList<Pair<String, Integer>> list = Lists.mutable.with(
        Tuples.pair("Three", 3),
        Tuples.pair("One", 1),
        Tuples.pair("Two", 2)
);
MutableMap<String, Pair<String, Integer>> map =
        list.groupByUniqueKey(Pair::getOne);

System.out.println(map);

MutableList<Pair<String, Integer>> sortedList =
        map.toSortedListBy(Pair::getTwo);

MutableSortedSet<Pair<String, Integer>> sortedSet =
        map.toSortedSetBy(Pair::getTwo);

MutableSortedBag<Pair<String, Integer>> sortedBag =
        map.toSortedBagBy(Pair::getTwo);

System.out.println(sortedList);
System.out.println(sortedSet);
System.out.println(sortedBag);

Outputs:

{One=One:1, Three=Three:3, Two=Two:2}
[One:1, Two:2, Three:3]
[One:1, Two:2, Three:3]
[One:1, Two:2, Three:3]

All of the toSorted methods above operate on the values only. This is why I stored the values as the Pair instances.

Note: I am a committer for Eclipse Collections.

Upvotes: 2

Related Questions