How to sort an array with customized Comparator in Java?



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
Updated on: 2019-07-30T22:30:25+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements