As ArrayList lies under collection in java. To Sort a collection in Java is so simple just use Collections.sort(Collection) to sort your values. The following code shows an example to sort the element of an ArrayList.
SortCollection.java:
-----------------------------
package in.anyforum;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortCollection {
public static void main(String[] args) {
List list = new ArrayList();
list.add(51);
list.add(40);
list.add(39);
list.add(78);
list.add(27);
list.add(16);
Collections.sort(list);
for (Integer integer : list) {
System.out.println(integer);
}
}
}
This is too easy because Integer implements the Comparable interface. This interface has the method compare which performs pairwise comparison of the elements and returns
-1: if the element is smaller then the compared element,
0: if it is equal and
1: if it is larger.
If you want to sort in a different way you can define your own implementation based on the Comparator interface like following.
MyIntComparable.java:
--------------------------------
package in.anyforum;
import java.util.Comparator;
public class MyIntComparable implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
SortCollection2.java:
-----------------------------
package in.anyforum;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortCollection2 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(59);
list.add(48);
list.add(37);
list.add(76);
list.add(25);
list.add(14);
Collections.sort(list, new MyIntComparable());
for (Integer integer : list) {
System.out.println(integer);
}
}
}
************************************* Note *************************************
For the above you could also have used the Collection.reverse() method call.
This approach is that you can sort any object by any attribute or even a combination of attributes. For example if you have objects of type Employee with an attribute income and salary in a collection you could define different implementations of Comparator and sort the objects according to your needs.
5