Java Collections Sort

During development, you come across the situation when you have to sort the collection. In many scenarios, data sorting is required like display sorted data or the user preference come should come on top. In this article, I show you how the Java collections sort method works with examples.

Java Collections sort

 

Java Collections sort method

Collections.sort() method is used to sort the collections in java. This method you can find in java.util package.  The existing list can be sorted using the collections.sort() method in ascending and descending order.

Syntax –

Collection .Sort(List mylist){
//List myList – pass the list to be sort.
}

Example –

Let say we have the below data in our List –

{“tutorials”, “geeks”, “A”}

Now you want to sort it so that it comes in ascending order means the word start from “a” comes first like below –

{“A”, “geeks”, “tutorials” }

 

Note – By default, collections.sort() method sorts the list in ascending order you can also sort it into descending order.

Java Collections sort example –

//Import the required package

import java.util.*;

public class collectionsort

{

    public static void main(String[] args)

    {

        // Create a list that you want to sort

        ArrayList<String> strItem = new ArrayList<String>();

        strItem.add("tutorials");

        strItem.add("geeks");

        strItem.add("Dear");

        /* Collections.sort method the sort the list in ascending order.*/

        Collections.sort(strItem);

        // Print the sorted list on console

        System.out.println("Sorted List :\n" + strItem);

    }

}

Output

Sorted List:
[Dear, geeks, tutorials]


Now let sort the collection in descending order using the collections.sort() method.

 

Java collections sort in descending order

I have used the same example just reverse the order of collection to sort the same in descending order using the Collections.reverseOrder() method. This is an optional parameter of the sort method.

Example –

//Import the required package
import java.util.*;

public class collectionsort
{
 public static void main(String[] args)
 {
 // Create a list that you want to sort
 ArrayList<String> strItem = new ArrayList<String>();
 strItem.add("tutorials");
 strItem.add("geeks");
 strItem.add("Dear");

 /* Collections.sort method the sort the list in ascending order.*/
 Collections.sort(strItem, Collections.reverseOrder());

 // Print the sorted list on console
 System.out.println("Sorted List :\n" + strItem);
 }
}


Output –

Sorted List:
[tutorials, geeks, Dear]

Here in both the java collections sort examples, I have used Array List. You can also use the array of elements first to convert the same in ArrayList and then sort. See below example –

 

//Import the required package
import java.util.*;

public class collectionsort
{
    public static void main(String[] args)
    {

         // create an array of string
        string arritems[] = {"Tutorials", "Geeks",

                             "Dear"};
        // Create a list from array string
        List myList =
          new ArrayList(Arrays.asList(arritems));

        /* Collections.sort method that sort the list.*/
        Collections.sort(myList);
        // Print the sorted list on console

        System.out.println("Sorted List:\n" + myList);

    }

}

Output

Sorted List:
[Dear, Geeks, Tutorials]

These are simple sort examples using the single collection what if you have to sort the list of lists in java.

 

Java sort list of lists

You have to create your own Comparator class and pass an instance to collections.sort() method.

 

class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> 

  @Override

  public int compare(List<T> o1, List<T> o2) {

    for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {

      int c = o1.get(i).compareTo(o2.get(i));

      if (c != 0) {

        return c;

      }

    }

    return Integer.compare(o1.size(), o2.size());

  }

}

List<List<Integer>> listOfLists = ...;
Collections.sort(listOfLists, new ListComparator<>());

 

//Here T is the Element of Comparable type that is to be compared.

 

Conclusion

This is how you can sort the list element in java. we have used the java collections sort method and reverseOrder() method to sort the given list in ascending and descending orders using code examples.