Eclipse Collections 中目前没有可用的直接 API 来根据 Map 的值对其进行排序。
另一种方法是使用flipUniqueValues 将地图翻转为MutableSortedMap。
MutableSortedMap<Integer, String> sortedMap = SortedMaps.mutable.empty();
sortedMap.putAll(mutableMap.flipUniqueValues());
System.out.println(sortedMap);
这将为您提供一个按Integer 键排序的MutableSortedMap。这里的输出将是:{1=One, 2=Two, 3=Three}
您也可以先将Pairs 存储在List 中,然后使用String 键对它们进行唯一分组以创建MutableMap。如果Map 中的值是Pair 实例,则它们可用于使用直接API 创建排序的List、SortedSet 或SortedBag。
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);
输出:
{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]
上述所有toSorted 方法仅对值进行操作。这就是我将值存储为 Pair 实例的原因。
注意:我是Eclipse Collections 的提交者。