|
Array Sort
The following code shows how to sort arrays using Arrays API.
|
package com.bethecoder.tutorials.collections;
import java.util.Arrays;
import java.util.Comparator;
public class ArraySortTest {
public static void main(String[] args) {
String [] strings = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX" };
//Natural sort
Arrays.sort(strings);
for (String str : strings) {
System.out.println(str);
}
System.out.println("----------------");
//Reverse sort
Arrays.sort(strings, new Comparator<String>() {
public int compare(String first, String second) {
return -first.compareTo(second);
//or
//return second.compareTo(first);
}
});
for (String str : strings) {
System.out.println(str);
}
}
}
|
| |
It gives the following output,
FIVE
FOUR
ONE
SIX
THREE
TWO
----------------
TWO
THREE
SIX
ONE
FOUR
FIVE
|
|