Below is an example on how to sort list in java. In order to sort list in java, the object inside the list should implement Comparable interface and we will use Collections utility class in Java. Implementing the Comparable interface gives you the flexibility to write your own logic on how the sorting will be done.
Basically, return a negative integer if you want the passed object(argument) to be after the current(this) object in the list, return 0 if both objects are the equal, and return positive integer if you want the passed object to be added first in the list before this object. Much better if we take an example:
Assuming we have List of object A, and we want to sort the list based on the integer property of object A in ascending.
public class A implements Comparable<A> { private int code; public A(int code) { this.code = code; } public int getCode() { return code; } @Override public int compareTo(A object) { if (this.code > object.getCode()) { return 1; } else if (this.code < object.getCode()) { return -1; } else { return 0; } } }
public class SortList { public static void main(String[] args) { A a1 = new A(1); A a2 = new A(2); A a3 = new A(3); A a4 = new A(4); List<A> list = new ArrayList<A>(); list.add(a3); list.add(a1); list.add(a4); list.add(a2); //sort the list Collections.sort(list); for(A a: list) { System.out.println(a.getCode()); } } }
The output would be:
1 2 3 4