eclipse-collections - 使用 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 中没有可用的直接 API 来Map
根据其值对 a 进行排序。
一种替代方法是将地图翻转为MutableSortedMap
using flipUniqueValues
。
MutableSortedMap<Integer, String> sortedMap = SortedMaps.mutable.empty();
sortedMap.putAll(mutableMap.flipUniqueValues());
System.out.println(sortedMap);
这会给你一个按键MutableSortedMap
排序的。Integer
这里的输出将是:{1=One, 2=Two, 3=Three}
您也可以先存储Pairs
,List
然后使用String
密钥对它们进行唯一分组以创建MutableMap
. 如果 中的值Map
是实例,则Pair
它们可用于创建 sortedList
或使用直接 API。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的提交者。
推荐阅读
- mysql - SQL:如何在不使用 rank() 的情况下理解解决方案代码?
- python - 如何使用python获取蒸汽覆盖信息
- windows - 如何使用 nim 语言在 Windows 上处理 taskkilll 命令?
- gatsby - Strapi 管理控制台页面工作并尝试无限期加载
- python - 如何在 Jupyter 笔记本 Python 中操作 2 列数据框
- c++ - clion ide的问题
- reactjs - 材质 UI 快速拨号 | 如何自定义工具提示
- bash - 在 bash 变量中存储 git branch -a 包括文件
- python - 如何从 Windows 中的数据框中删除整行?
- php - foreach 循环只打印 MySQL 表中的一条记录