2019-08-13
How to sort some specific element in an array using comparator
stackoverflow
Question

I am trying to sort an array in a specific order. if number % 10 is equal 0 then it will come first and for the rest, if number mod 10 is greater it will come first.

Collections.sort(arr,new Comparator<Integer>(){
   public int compare(Integer e1, Integer e2) {
       if(e1 %10 == 0 && e2 %10 != 0  || (e2 %10 == 0 && e1 %10 != 0)  
       || e1 % 10 ==0 || e2 % 10 ==0){
           return -1;
       }else{
           if(e1 % 10 < e2 % 10){
               return 1 ;
           }else{
               return -1 ;
           }
       }
   }});

input : [120, 20, 35, 7, 29]

output: [29, 7, 35, 20, 120]

expected: [120, 20, 29, 7 , 35]

Answer
1

The simplest way to do this with an explicit comparator is:

public int compareTo(Integer a, Integer b) {
  int cmp = Boolean.compare(a % 10 != 0, b % 10 != 0);
  if (cmp != 0) {
    return cmp;
  }
  return a.compareTo(b);
}

Using Boolean.compare(a % 10 != 0, b % 10 != 0) finds if the last digit is zero or not: if a does not end with zero but b does, a positive value is returned, so a will be sorted after b.

If the either both end with a zero, or neither ends with a zero, the numbers are compared naturally.

How to sort some specific element in an array using comparator
See more ...