【问题标题】:Using the Eclipse Collections library, how do I sort MutableMap on the value?使用 Eclipse Collections 库,如何根据值对 MutableMap 进行排序?
【发布时间】:2019-02-26 00:02:19
【问题描述】:

假设我有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&lt;String, Integer&gt;,但已排序/排序,以便第一个元素是(“One”,1),第二个元素是(“Two”,2),和第三个元素(“三”,3)。

【问题讨论】:

    标签: eclipse-collections


    【解决方案1】:

    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 创建排序的ListSortedSetSortedBag

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

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 2017-09-21
      • 2020-01-10
      • 2014-12-07
      • 2015-01-05
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      相关资源
      最近更新 更多