How to sort a List in Java?

UPDATED: 15 November 2014
Collections Framework Java


What is List?
List is an Interface provided by Collections framework. List used store sequence of elements. User has precise control over list like where in the list each element is inserted. Used can access list by their index(position).

Source Code
Below code gives you example on how you can sort a List.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author javaQuery
 */
public class SortingListExample {

    public static void main(String[] args) {
        /* Create list of Integer */
        List listInteger = new ArrayList();
        /* Add elements in listInteger */
        listInteger.add(3);
        listInteger.add(6);
        listInteger.add(4);
        listInteger.add(5);
        listInteger.add(1);
        listInteger.add(2);

        System.out.println("Initial Integer List: " + listInteger);
        /* Use Collections to sort a list */
        Collections.sort(listInteger);
        System.out.println("Sorted Integer List: " + listInteger);

        /* Create list of String */
        List listString = new ArrayList();
        /* Add elements in listString */
        listString.add("o");
        listString.add("i");
        listString.add("u");
        listString.add("e");
        listString.add("a");

        System.out.println("Initial String List: " + listString);
        /* Use Collections to sort a list */
        Collections.sort(listString);
        System.out.println("Sorted String List: " + listString);

        /* Create list of Object */
        List listMixed = new ArrayList();
        /* Add elements in listMixed */
        listMixed.add("u");
        listMixed.add("5");
        listMixed.add("a");
        listMixed.add("6");
        listMixed.add("1");
        listMixed.add("z");

        System.out.println("Initial Mixed List: " + listMixed);
        /* Use Collections to sort a list */
        Collections.sort(listMixed);
        System.out.println("Sorted Mixed List: " + listMixed);
    }
}

Output
Initial Integer List: [3, 6, 4, 5, 1, 2]
Sorted Integer List: [1, 2, 3, 4, 5, 6]

Initial String List: [o, i, u, e, a]
Sorted String List: [a, e, i, o, u]

Initial Mixed List: [u, 5, a, 6, 1, z]
Sorted Mixed List: [1, 5, 6, a, u, z]

  • Sorting Integer List: It'll sort integer values from lowest to highest (1,2,3...n).
  • Sorting String List: It'll sort string values from lowest to highest (a,b,c....z).
  • Sorting Mixed List: It'll sort integer values followed by string values (1,2,3...n,..a,b...z).

0 comments :