collection sort int code example

Example 1: how to sort collection in java

// Use Collections.sort()
import java.util.*;
ArrayList<String> al = new ArrayList<String>();
al.add("teach");
al.add("sleep");
al.add("geek");
Collections.sort(al);//just pass any collection object reference
System.out.println(al);//output :- [geek,sleep,teach]

or
/*
ArrayList<Integer> intal = new ArrayList<Integer>();
al.add(4);
al.add(8);
al.add(2);
Collections.sort(intal);
System.out.println(intal);//output :- [2,4,8]
*/

Example 2: Compare integers java sort

public class AgeComparatorDesc implements Comparator<Student> {

  @Override
  public int compare(Student o1, Student o2) {
    if (o1.age > o2.age) {
        return -1;
    } else if (o1.age < o2.age) {
        return 1;
    }    
     return 0;
  }

}