如何使用 Java 8 的 parallelSort() 对地图列表进行排序

How can I use parallelSort() of Java 8 to sort List of Maps

我知道如何使用 ComparatorCollections.sort() 对任何类型的对象进行排序,但我想知道如何使用 Arrays.parallelSort() 对地图列表进行排序?因为它只能对普通数组进行排序。

这是我使用 Comparator

对其进行排序的代码
List<Map<String, Integer>> employees = new ArrayList<Map<String, Integer>>() {{
    add(new HashMap<String, Integer>() {{put("position",5); put("id2", 9);}});
    add(new HashMap<String, Integer>() {{put("position",1); put("id2", 1);}});
    add(new HashMap<String, Integer>() {{put("position",2); put("id2", 2);}});
    add(new HashMap<String, Integer>() {{put("position",4); put("id2", 5);}});
    add(new HashMap<String, Integer>() {{put("position",1); put("id2", 1);}});
    add(new HashMap<String, Integer>() {{put("position",4); put("id2", 7);}});
}};

Comparator<Map<String, Integer>> comparator = new Comparator<Map<String, Integer>>() {
        @Override
        public int compare(Map<String, Integer> o1,Map<String, Integer> o2) {
                int nr1 = o1.get("id2");
                int nr2 = o2.get("id2");
                return Integer.compare(nr2, nr1);
        }
};

Collections.sort(employees,comparator);

for (Map<String, Integer> s : employees){
    System.out.println(s);
}

Arrays.parallelSort 确实有一个名为 parallelSort(T[] a,Comparator<?super T> c) 的方法,但我不知道如何正确使用它。

到目前为止我已经试过了,

Arrays.parallelSort(new ArrayList<Map<String, Integer>>(employees.size()), comparator);

我当然会得到这个错误,

The method parallelSort(T[], Comparator<? super T>) in the type Arrays is not applicable for the arguments (ArrayList<Map<String,Integer>>, Comparator<Map<String,Integer>>)

我很好奇是否可以使用 parallelSort 对此类数据进行排序?

P.S: 我也知道用Java8stream().sorted排序但是我不想用

编辑: 我正在按降序排列 id2

对于您在问题中显示的具体示例,您可以简单地写:

employees.parallelStream()
        .sorted((m1, m2) -> Integer.compare(m2.get("id2"), m1.get("id2")))
        .forEachOrdered(System.out::println);

但请注意,它可能会在后台调用 Arrays#parallelSort