我知道如何使用Comparator
和Collections.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:我也知道如何使用Java 8 stream().sorted
进行排序,但我不想使用它。
修改:我按降序排序id2
。
答案 0 :(得分:2)
对于您在问题中显示的具体示例,您只需写下:
employees.parallelStream()
.sorted((m1, m2) -> Integer.compare(m2.get("id2"), m1.get("id2")))
.forEachOrdered(System.out::println);
但请注意,它可能会在后台调用Arrays#parallelSort
。