【问题标题】:converting a set to an arrayList with sorting operations使用排序操作将集合转换为 arrayList
【发布时间】:2018-12-09 20:02:45
【问题描述】:

我有一个Map<Integer, Set<Integer>>,我想按递增顺序获取键列表作为 ArrayList。

例如我的地图:

Key|Value
2--->set1
1--->set2
5--->set3

我想得到数组列表:[1,2,5]

public class Example {
     public static void main( String[] args ) {
         Map<Integer,Set<Integer>> map = new HashMap<>();
         Set<Integer> set1 = Stream.of(1,2,3).collect(Collectors.toSet());
         Set<Integer> set2 = Stream.of(1,2,3).collect(Collectors.toSet());
         Set<Integer> set3 = Stream.of(1,2,3).collect(Collectors.toSet());
         map.put(2,set1);
         map.put(1,set2);
         map.put(5,set3);


         //what i have done:
         List<Integer> list = map.keySet()
                                 .stream()
                                 .collect(Collectors.toCollection(ArrayList::new));
         list.sort((a,b)->a>b?b:a);
         System.out.println(list);

     }
}

这个例子做我想做的,但我正在寻找一种在收集元素时进行排序的解决方案?

【问题讨论】:

    标签: java arraylist java-stream


    【解决方案1】:

    使用sorted 方法:

    List<Integer> list = map.keySet()
                    .stream()
                    .sorted()
                    .collect(Collectors.toCollection(ArrayList::new));
    

    【讨论】:

    • 或者只是List&lt;Integer&gt; list = new ArrayList&lt;&gt;(map.keySet()); list.sort(null);
    【解决方案2】:

    更好的是,只需像这样将 HashMap 更改为 TreeMap:

    Map<Integer,Set<Integer>> map = new TreeMap<>();
    

    引用文档“基于红黑树的 NavigableMap 实现。地图根据其键的自然顺序或在地图创建时提供的 Comparator 进行排序,具体取决于使用的构造函数。”如果是整数,您将具有自然顺序:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 2012-08-27
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多