Priority Queue ordering generates different result compared to Arrays.sort when using the same comparator. What changes should I make to the comparator for priority queue to give result similar to current Arrays.sort?
public static void main(String[] args) {
String[] logs = {"aa 1 2 3 4","hi small van","cc1 2 2","abc cat dog","i9 hat cat"};
reorderLogs(logs);
}
public static String[] reorderLogs(String[] logs) {
Comparator<String> myComp = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String[] s1 = o1.split(" ",2);
String[] s2 = o2.split(" ",2);
Boolean isDigit1 = Character.isDigit(s1[1].charAt(0));
Boolean isDigit2 = Character.isDigit(s2[1].charAt(0));
if(isDigit1 && isDigit2){
return 0;
}
if(isDigit1){
return 1;
}
if(isDigit2){
return -1;
}
int x = s1[1].compareTo(s2[1]);
if(x == 0){
return s1[0].compareTo(s2[0]);
}
return x ;
}
};
Queue<String> q = new PriorityQueue<>(myComp);
q.addAll(Arrays.asList(logs));
Arrays.sort(logs,myComp);
String[] op = new String[q.size()];
op = q.toArray(op);
return op;
}