How to sort an array with customized Comparator in Java?

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our string array and we need to sort it:

String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" };

Within the sort() method, create a customized comparator to sort the above string. Here, two strings are compared with each other and the process goes on:

Arrays.sort(str, new Comparator < String > () {
   public int compare(String one, String two) {
      int val = two.length() - one.length();
      if (val == 0)
      val = one.compareToIgnoreCase(two);
      return val;
   }
});

Example

import java.util.Arrays;
import java.util.Comparator;
public class Demo {
   public static void main(String[] args) {
      String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" };
      System.out.println("Array...");
      for (String res : str)
         System.out.print(res + " ");
      Arrays.sort(str, new Comparator<String>() {
         public int compare(String one, String two) {
            int val = two.length() - one.length();
            if (val == 0)
               val = one.compareToIgnoreCase(two);
            return val;
         }
      });
      System.out.println("\nSorted array...");
      for (String res : str)
      System.out.print(res + " ");
   }
}

Output

Array...
Tom Jack Harry Zen Tim David
Sorted array...
David Harry Jack Tim Tom Zen
raja
Published on 25-Apr-2019 12:47:24
Advertisements