In this example, we can learn how to sort an array using comparator.
Source Code
package com.beginner.examples;
import java.util.Arrays;
import java.util.Comparator;
public class SortArray {
public static void main(String[] args) {
//Create String array object.
String[] strArr = {"Alice", "Jack", "Bob", "Jerry"};
/*
* Use the method Arrays.sort()
* to sort an Array of objects by passing Comparator object,
* where Comparator holds the sorting logic.
*/
Arrays.sort(strArr, new Comparator() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
for(String str:strArr){
System.out.println(str);
}
}
}
Output:
Alice
Bob
Jack
Jerry
References
Imported packages in Java documentation: