Skip to main content
 首页 » 编程设计

eclipse-collections中使用 Eclipse Collections 库,如何对 MutableMap 的值进行排序

2025年12月25日34zdz8207

假设我有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),第三个元素为 ("Three", 3)。

请您参考如下方法:

当前 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 实例,则它们可用于创建排序的 ListSortedSet或使用直接 API 的 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 的提交者.