Java: Sorting Integer Arraylist using Collections.sort



Step 1: Define the Comparator that compares integer values.

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));
	}
}

Step 2: Call the Comparator in Collections.Sort.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Simple2 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(4);
		list.add(3);
		list.add(7);
		list.add(2);
		list.add(1);
		Collections.sort(list, new MyIntComparable());
		for (Integer integer : list) {
			System.out.println(integer);
		}
	}
}