Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
