Collections.sort() – Ways to Sort a List in Java

In our previous article, we have discussed all the methods of the List in Java Programming Language. Now in this article, we are going to discuss the methods to sort the List elements in Java Programming Language like Collections.sort(). In Java Programming Language, the List provides the functionality to the developer to store the duplicate and multiple null values in a single List. The real-time programming paradigm List also provides the functionality of traversing the list in both directions. Sometimes the programmer needs to store the list before processing its elements. Let’s discover how we can sort the elements of a list in Java.

collections.sort()

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is a Java List?

The List is the subinterface of the Collections interface. List interface imported from Java.util.List as the child interface of Collections. A List is the ordered collection of objects i.e. in the list the order of the elements is maintained. It also supports having duplicate values in it. In this article, we will implement some methods of List and Sort the ArrayList.

sort list in java

Collections.sort() method in Java

To sort the list in Java we have to understand the working of the Collections.sort() method which is present in java.util.Collections class. The java.Collections.sort() is very similar to the java.util.Arrays.sort() method; rather it is much better than it. The java.Collections.sort() method is also used to sort the linked list, array, queue, and other data structures.

If we talk about the working of this method, then the method works on ASCII values. The java.Collections.sort() method sorts the list elements by comparing the ASCII values of the elements. The method compares the first element by its ASCII values, if it matches then it compares the second element and so on.

Code to sort the list in ascending order with Collections.sort() method:

package com.techvidvan.listsort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListSort_Java //Class for sorting the List in Java
{
  public static void main(String[] args) {
    List < String > myList = new ArrayList < String > ();
    myList.add("W");
    myList.add("T");
    myList.add("A");
    myList.add("G");
    myList.add("I");
    myList.add("B");
    myList.add("Z");
    myList.add("0");
    myList.add("U");
    myList.add("7");

    System.out.println("The unsorted List is:");

    for (String myStr: myList) {
      System.out.print(" " + myStr);
    }

    //Collections.sort() are used to sort the List
    Collections.sort(myList);

    System.out.println("\nThe Sorted List is");

    for (String myStr: myList) {
      System.out.print(" " + myStr);
    }
  }
}

Output:

The unsorted List is:
W T A G I B Z 0 U 7
The Sorted List is:
0 7 A B G I T U W Z

Collections.reverseOrder() Method in Java

To sort the list in reverse order, we have to discuss the reverseOrder() method which is also present in the class Collections.reverseOrder(). The working of this method is very similar to the Collections.sort() method but unlike the Collections.sort() method, it sorts the list elements in reverse order of the natural ordering on the collections of objects. The method compares the elements according to the ASCII values and arranges them in reverse order.

package com.techvidvan.listsort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListSort_Java //Class for sorting the List in Java
{
  public static void main(String[] args) {
    List < String > myList = new ArrayList < String > ();
    myList.add("W");
    myList.add("T");
    myList.add("A");
    myList.add("G");
    myList.add("I");
    myList.add("B");
    myList.add("Z");
    myList.add("0");
    myList.add("U");
    myList.add("7");

    System.out.println("The unsorted List is:");

    for (String myStr: myList) {
      System.out.print(" " + myStr);
    }

    //Collections.sort() are used to sort the List
    Collections.sort(myList, Collections.reverseOrder());
    System.out.println("\nThe Sorted List in reverse order is:");
    for (String myStr: myList) {
      System.out.print(" " + myStr);
    }
  }
}

Output:
The unsorted List is:
W T A G I B Z 0 U 7
The Sorted List in reverse order is:
Z W U T I G B A 7 0

The sorted() Method in Java

Another way to sort the list is by Stream class which is present in the java.util package. The stream class provides a method named as sorted() which sorts the list in natural order by comparing ASCII values as we discussed in the previous section. The sorted() method used to sort the list of objects or collections of the objects in the ascending order. If the collections of the objects are comparable then it compares and returns the sorted collections of objects; otherwise it throws an exception from java.lang.ClassCastException.

Code to Sort elements of the list alphabetically with the sorted() method:

package com.techvidvan.listsort;
import java.util. * ;
import java.util.stream. * ;

public class ListSort_Java // Class for sorting the List in Java
{
  public static void main(String[] args) {
    List < String > myList = Arrays.asList("Joy", "Alice", "Bob", "Max", "Charles", "Katty");
    System.out.println("Sorted List is: ");
    List < String > sortList = myList.stream().sorted().collect(Collectors.toList());
    sortList.forEach(System.out::println);
  }
}

Output:
Sorted List is:
Alice
Bob
Charles
Joy
Katty
Max

Comparator.reverseOrder() Method in Java

For reverse order sorting with the help of sorted() method, we have to use another method named Comparator.reverseOrder(). The reverseOrder() method is declared in the Comparator Interface of Java which defines in the java.util package.

The method sorted() returns the collection of objects in a sorted manner and after that, we apply Comparator.reverseOrder() method that converts the sorted objects into the reverse natural ordering. When we try to compare Null with the help of Comparator Interface it throws the NullPointerException.

Code to Sort elements of the list alphabetically in reverse order with the sorted() method:

ackage com.techvidvan.listsort;
import java.util. * ;
import java.util.stream.Collectors;

public class ListSort_Java_Reverse // Class for sorting the List in Reverse Order in Java
{
  public static void main(String[] args) {
    List < String > myList = Arrays.asList("Joy", "Alice", "Bob", "Max", "Charles", "Katty");
    System.out.println("Sorted List in Reverse Order is: ");
    List < String > sortList = myList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    sortList.forEach(System.out::println);
  }
}

Output:
Sorted List in Reverse Order is:
Max
Katty
Joy
Charles
Bob
Alice

Comparator.naturalOrder() Method in Java

The Comparator.naturalOrder() method is used to compare the Comparable objects in natural order(ascending order). The Comparator that is returned as a result of the comparison is Serializable. When we compare null with objects, this method throws a NullPointerException. This method is available from Java 8.

Syntax of Comprator.naturalOrder() method:

static < T extends Comparable < ?super T >> Comparator < T > naturaOrder()

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

Code to sort elements in natural order using the Comparator.naturalOrder() method:

package com.techvidvan.listsort;
import java.util. * ;
public class NaturalOrderDemo {
  public static void main(String[] args) {
    List < String > countryNames = Arrays.asList("Nepal", "India", "Italy", "Japan", "", "Bhutan");
    List < String > countryNames1 = Arrays.asList("Nepal", "india", "China", "Japan", "", "bhutan");
    System.out.println(countryNames);
    countryNames.sort(String.CASE_INSENSITIVE_ORDER);
    System.out.println(countryNames1);
    countryNames.sort(Comparator.naturalOrder());
    System.out.println(countryNames);
    countryNames1.sort(Comparator.naturalOrder());
    System.out.println(countryNames1);
  }
}

Output:
[Nepal, India, Italy, Japan, , Bhutan]
[Nepal, india, China, Japan, , bhutan]
[, Bhutan, India, Italy, Japan, Nepal]
[, China, Japan, Nepal, bhutan, India]

Conclusion

In this article, we learned to sort the list element with the help of many methods like collections.sort(). We implemented each method with the help of Java programs. Then we also sorted the elements in the reverse order. We hope, now you can easily learn to sort the list elements in either ascending or descending order.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.