I know how to sort any kind of object using Comparator
and Collections.sort()
but I want to know how can I use Arrays.parallelSort()
to sort the list of Maps ? since it is capable of sorting only normal arrays.
This is my code to sort it using 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
does have a method called parallelSort(T[] a,Comparator<?super T> c)
but I don't know how to use it properly.
I have tried this so far,
Arrays.parallelSort(new ArrayList<Map<String, Integer>>(employees.size()), comparator);
Ofcourse I would get this error,
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>>)
I am just curious if such type of data can be sorted using parallelSort
?
P.S: I also know how to use Java 8 stream().sorted
for sorting but I don't want to use it.
Edit: I am sorting id2
in descending order.