In Java, there are various data structures for storing and processing multiple elements such as Array, ArrayList, etc. Oftentimes, the developers are required to arrange the element in a specific order to perform data-related operations on it. This arrangement of elements following a specific order is called sorting in programming languages. In Java, there are several methods for sorting a List. This article discusses 7 different methods for sorting a List of elements in Java using built-in methods of different public classes.
Method 1: Sort a List Using Collections.sort()
In Java, the Collections interface provides a unified architecture of different classes and methods for working with a group of objects. With this, the developers can perform various data manipulating operations such as storing, deleting, modifying, creating, searching, etc on a collection of objects. Execute the below code to sort the list using the Collections interface.
Utilize the following import statements to include the Collections, List, and ArrayList classes from the “java.util” package:
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
Create a “numList” object of the List class to store multiple elements of integer data type. The add() method adds the following values to the list at different indexes:
List <Integer> numList = new ArrayList<Integer>(); //creating a List
//adding numbers
numList.add(5);
numList.add(6);
numList.add(3);
numList.add(7);
The sort() method is a static function of the Collections class. The sort() method modifies and sorts the “numList” and returns it which is then printed using the println() method:
//Using Collection.sort()
Collections.sort(numList);
System.out.println("Sorted List is " + numList);
Output
The output is given as follows:
Method 2: Sort a List Using Stream.sorted()
The Stream API in Java was introduced in Java 8 and provides multiple different methods for working with the collection of objects. You can utilize the Stream API static methods to sort a Java List. For this, the sorted() method of the Stream API is used.
In the given code snippet, the Collections, ArrayList, and List classes are imported from the “java.util” package. The Collectors class is also imported from the java.util.stream package:
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;
Within the main() function, a List class’s instance of “String” data type is created which is named “numList2”. The object “numList2” invokes the add() function to add the following elements as shown in the code below:
List <String> numList2 = new ArrayList<String>(); //creating a List
//adding numbers
numList2.add("A");
numList2.add("B");
numList2.add("D");
numList2.add("C");
Inside the print statement, the “numList2” invokes the stream() method to convert the list into a stream. The sorted() method arranges the elements in their natural order i.e., smallest to largest number or alphabetical order. The collect() method then collects the elements and transforms them into a List. The output is printed on the console:
System.out.println("Sorted List by stream sorted " + numList2.stream().sorted().collect(Collectors.toList()));
Output
The output of the code is given as follows:
Method 3: Sort a List Using Comparator.reverseOrder()
A Comparator in Java is an interface that provides different methods for sorting the List in Java. Different methods of this interface provide pre-defined functionality for sorting the elements or comparing them, etc. The code given below provides a demonstration of using the Comparator interface to sort the elements of List in Java.
The import statement includes all the essential classes and dependencies from the “java.util” package:
import java.util.*;
import java.util.stream.Collectors;
The List class is used to create an instance “numList” using the “new” keyword. The add() function is invoked to add the specified elements to the numList List:
List <Integer> numList= new ArrayList<>(); //List is created
numList.add(2);
numList.add(7);
numList.add(1);
numList.add(5);
The print statement then prints the elements of the List after sorting by calling the sorted function of the Stream API. The Comparator.reverseOrder() sorts the string in descending order which is then printed by using the print statement:
//String is sorted in Reverse Order
System.out.println("Sorted List is " + numList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()));
Output
The output of the code is as follows:
Method 4: Sort a List Using a Comparator.naturalOrder()
This code provides another method of Comparator interference for sorting the List in a specific manner. For this, import all the necessary dependencies and classes such as Stream, List, etc., from the java.util package:
import java.util.*;
In this code snippet, the List class’s instance “numList” is created and initialized. The add() method called by the “numList” adds the following elements to the List “numList”:
List <Integer> numList= new ArrayList<>(); //List is created
numList.add(2);
numList.add(7);
numList.add(1);
numList.add(5);
The print statement is used to print the output after sorting the List elements. The Comparator.naturalOrder() arranges the elements of the List in a natural order which is then displayed as output on the Console:
//String is sorted in Reverse Order
System.out.println("Sorted List is " + numList.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList()));
Output
The output of the code is given in the following snapshot:
Method 5: Sort a List Using Collections.reverseOrder()
In this code, the Collections, List, and ArrayList classes are imported from java.util package using the following import statement:
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
The List class’s object “numList” of the “Integer” data type is created. The “numList” invokes a static method “add()” that adds/inserts the desired elements in the numList:
List <Integer> numList= new ArrayList<>(); //List is created
numList.add(-1);
numList.add(10);
numList.add(-40);
numList.add(20);
numList.add(0);
numList.add(100);
The sort function from the Collections class is called with two parameters i.e., numList and the Collections.reverseOrder() method. The reverseOrder() is a static method of the Collections class that reverses/sorts the List in descending order. The output is then printed using the println() method:
//String is sorted in Reverse Order
Collections.sort(numList, Collections.reverseOrder());
System.out.println("List sorted in Reverse Order " + numList );
Output
The output of the code is given as follows:
Method 6: Sorting a List Using List.sort()
The List data structure contains multiple elements of a specific data type. The elements are stored at the contiguous memory location and can be accessed via the get() method by specifying the index of the element. The List works similarly to the “ArrayList” which grows and shrinks according to the storage and user requirements.
The following import statement includes the Collections, List, and ArrayList classes from java.util package:
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
An instance of the “String” data type is created from the List class. The add() function is called to add the following string elements to the List as shown in the code below:
List <String> numList2 = new ArrayList<String>(); //creating a List
//adding numbers
numList2.add("A");
numList2.add("B");
numList2.add("D");
numList2.add("C");
The sort() function is called using the numList2 object. The “null” value is passed to it as a parameter. The List “numList2” is modified and the output is printed using the println() method:
//Using List.sort()
numList2.sort(null);
System.out.println("Sorted List by using List.sort() " + numList2);
Output
The output of the code is shown below:
Method 7: Sort a List Using Guava Ordering Class
Guava is a third-party open-source core library provided by Google to improve the code functionality and reduce coding errors. It contains multiple static functions and several public classes for performing distinct functions.
To use the functions of the Guava Library, add the below-stated dependency in your “pom.xml” or “build.gradle” files of Maven or Gradle projects:
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
</dependencies>
Here, the dependency has been added to the pom.xml file:
In the main code, the given import statement includes the List and Arrays class from the “java.util” package. Similarly, the Ordering class is imported from the Guava’s “com.google.common.collect” package:
import java.util.List;
import com.google.common.collect.Ordering;
import java.util.Arrays;
In the following code snippet, an instance of the List class “programLanguages” is initialized with the given values. Inside the println() method, the Ordering class invokes the natural() function. This method will arrange the elements in a natural order following the lexicographical manner (alphabetical) and the sortedCopy() method will sort the “programLanguages” array. The output will be then printed:
List<String> programLanguages = Arrays.asList("Java", "Python", "C++", "JavaScript");
System.out.println("Sorted List is : " + Ordering.natural().sortedCopy(programLanguages));
Output
The output of the code is given as follows:
That is all from this guide.
Conclusion
The term sorting refers to arranging/placing the elements of a collection in a specific manner. In Java, several approaches are used for sorting a List, such as Collections.sort(), Comparator.naturalOrder(), Stream.sorted(), List.sort(), or Ordering class of the Guava Library. By sorting a List, it is easy to access and manipulate the elements of a List. It is an important operation in Data management, data searching, or data manipulation. This article provides multiple different methods for sorting a List in Java with a practical demonstration of it.