How to Sort an ArrayList with Comparator in Java

By default, items in ArrayList are displayed in the order in which they are inserted into the list, but sometimes you need to browse these items in ascending or descending order. This code implements the Collections.sort() which sorts a Arraylist in ascending and descending order.

Sort ArrayList in ascending order

import java.util.ArrayList; 
import java.util.Collections;

public class Tri {

public static void main(String[] args) {
ArrayList unsorted = new ArrayList();
nonsort.add("01");
nonsort.add("0A");
unsorted.add("0B");
unsorted.add("ETX");
unsorted.add("00");
unsorted.add("0C");
nonsort.add("NUL");
unsorted.add("05");
unsorted.add("19");
unsorted.add("0001011");

System.out.println("Before sorting");
for(int i=0; i < unsorted.size(); i++)
System.out.println(unsorted.get(i));

System.out.println("\nAfter sorting");
Collections.sort(unsorted);
for(int i=0; i < unsorted.size(); i++)
System.out.println(unsorted.get(i));
}
}
Output:

Before tri
01
0A
0B
ETX
00
0C
NUL
05
19
0001011
< br />After sorting
00
0001011
01
05
0A
0B
0C
19
ETX
NUL

Sort ArrayList in descending order

The Collections class has another method Collections.sort(List< T>, Comparator< T>) which allows you to sort an ArrayList in ascending and descending order. This function uses an object comparator that compares two objects each time with the function o1.compareTo(o2).

import java.util.ArrayList; 
import java.util.Collections;
import java.util.Comparator;

public class Tri {

public static void main(String[] args) {
ArrayList unsorted = new ArrayList();
unsorted.add("11000000");
unsorted.add("10101000");
unsorted.add("00000001");
unsorted.add("00001111");
nontrié.add("00001100");
unsorted.add("00001111");
unsorted.add("11111111");
nonsort.add("11111100");
unsorted.add("00000000");
unsorted.add("00000011");
unsorted.add("00001110");

System.out.println("Before sorting");
for(int i=0; i < unsorted.size(); i++)
System.out.println(unsorted.get(i)+" ");

System.out.println("\nAfter sorting");

Collections.sort(nonsort, new Comparator() {
@Override
public int compare(String s1, String s2)
{
/*s2 compared to s1 so that the order is descending
return s2.compareTo(s1);
}
});
for(int i=0; i < unsorted.size(); i++)
System.out.println(unsorted.get(i)+" ");
}
}
Output:

Before Sort
11000000
10101000
00000001
00001111
00001100
00001111
11111111
11111100
00000000
00000011
00001110

After sort
11111111
11111100
11000000
10101000
00001111
00001111
00001110
00001100
00000011
00000001
00000000
References:
American Standard Code for Information Interchange
Documentation Collections.sort
stackOverFlow:How to sort an ArrayList in java