 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
 