import java.util.Arrays;
import java.util.Collections;
class MyObject {
public static void main(String args[]) {
String iArr[] = { "ca", "Ac", "aC" };
Arrays.sort(iArr);
for (String number : iArr) {
System.out.println("ASC = " + number);
}
Arrays.sort(iArr, Collections.reverseOrder());
for (String number : iArr) {
System.out.println("DESC = " + number);
}
}
}
|
Output
ASC = Ac
ASC = aC
ASC = ca
DESC = ca
DESC = aC
DESC = Ac
|
Output
Before sorting...
[Kumar, Dennis, John, Ravi, Zen]
After sorting...
[Dennis, John, Kumar, Ravi, Zen]
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortingUsingComparator {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Kumar");
names.add("Dennis");
names.add("John");
names.add("Ravi");
names.add("Zen");
System.out.println("Before sorting...");
System.out.println(names);
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.compareTo(o2) > 0) {
return 1;
}
else {
return 0;
}
}
});
System.out.println("After sorting...");
System.out.println(names);
}
}
|