首页 > 解决方案 > 使用 Eclipse Collections 库,如何根据值对 MutableMap 进行排序?

问题描述

假设我有MutableMap<String, Integer>,并且我想对Integer值进行排序。

用这个库推荐的方法是什么?Eclipse Collections 库是否有实用程序或方法或推荐的方法来解决这个问题?

例如,假设:

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

我想最终得到一个MutableMap<String, Integer>包含相同元素,但排序/排序的第一个元素(“One”,1),第二个元素(“Two”,2)和第三个元素(“三”,3)。

标签: eclipse-collections

解决方案


目前 Eclipse Collections 中没有可用的直接 API 来Map根据其值对 a 进行排序。

一种替代方法是将地图翻转为MutableSortedMapusing flipUniqueValues

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

System.out.println(sortedMap);

这会给你一个按键MutableSortedMap排序的。Integer这里的输出将是:{1=One, 2=Two, 3=Three}

您也可以先存储PairsList然后使用String密钥对它们进行唯一分组以创建MutableMap. 如果 中的值Map是实例,则Pair它们可用于创建 sortedList或使用直接 API。SortedSetSortedBag

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的提交者。


推荐阅读