List sorting
In this chapter you will learn:
- How to Sort a list
- Sort elements of ArrayList
- Sort elements of Vector
- Sort ArrayList in descending order using comparator
Sort a list
List is a sequence of elements. We can search a list with a default comparator or we can use a specified comparator.
static<T extends Comparable<? super T>>void sort(List<T> list)
Sorts the specified list into ascending order, according to the natural ordering of its elements.static<T> void sort(List<T> list, Comparator<? super T> c)
Sorts the specified list according to the order induced by the specified comparator.
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
/* j a v a 2 s. c o m*/
public class Main {
public static void main(String args[]) {
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(-8);
ll.add(20);
ll.add(-20);
ll.add(8);
Comparator<Integer> r = Collections.reverseOrder();
Collections.sort(ll, r);
System.out.print("List sorted in reverse: ");
System.out.print(ll);
}
}
The output:
Sort elements of ArrayList
In the following code we sort anArrayList
.
import java.util.ArrayList;
import java.util.Collections;
/*from ja v a2 s . co m*/
public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("java2s.com");
Collections.sort(arrayList);
System.out.println(arrayList);
}
}
The output:
Sort elements of Vector
import java.util.Vector;
import java.util.Collections;
/*from j a v a 2 s.c o m*/
public class Main {
public static void main(String[] args) {
Vector v = new Vector();
v.add("1");
v.add("3");
v.add("5");
v.add("2");
v.add("java2s .com ");
Collections.sort(v);
System.out.println(v);
}
}
The output:
Sort ArrayList in descending order using comparator
The following code sorts
ArrayList
in descending order.
The control over descending order or ascending order is through
different comparators.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/*from j a va2 s .c o m*/
public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("java2s.com");
Comparator comparator = Collections.reverseOrder();
System.out.println("Before: " + arrayList);
Collections.sort(arrayList, comparator);
System.out.println("After sorting: " + arrayList);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » List