- How to Sort a List in Java – Java List Sorting Example
- How to Use the Collections.Sort() Method in Java
- How to Use the List.Sort() Method in Java
- How to Use the stream.sorted() Method in Java
- Conclusion
- Sorted List Java Example
- 1. SimpleSortExample
- 2. SortWithComparatorExample
- 3. ReverseSortExample
- 4. Sort objects
- 5. Array.sort() vs Collection.sort()
- 6. Download the Source Code
- How to Sort a List in Java
- Java Sort List
- Java Sort List of Objects
- Sort a List in Java using Comparator
- Summary
How to Sort a List in Java – Java List Sorting Example
Edeh Israel Chidera
Sometimes data needs to be arranged in a specific order so it’s easier to understand, search, and process.
We call this process sorting. Sorting refers to arranging data in a specific order using certain criteria. You can sort different types of data, including numbers, strings, and objects. Java provides built-in methods for sorting, such as the Collections classes.
Sorting data in Java could be useful in an e-commerce application where a list of products needs to be displayed to the user. The products can be sorted in various ways depending on the requirements the user sets such as price, rating, brand, and so on.
For example, if the user wants to see all the products sorted by price in ascending order, the application can use a sorting algorithm to arrange the products in that order. This way, when the user views the products, they will be able to see the cheapest products first and make a purchase decision accordingly.
This article will look at various methods for sorting a list in Java.
How to Use the Collections.Sort() Method in Java
One of the most common ways to sort data in Java is to use the Collections.sort() method. It sorts a list in ascending order by default.
Here is an example of how to use the Collections.sort() method to sort a list of integers:
import java.util.Collections; import java.util.List; import java.util.ArrayList; public class Main < public static void main(String[] args) < Listnumbers = new ArrayList(); numbers.add(3); numbers.add(1); numbers.add(4); numbers.add(2); Collections.sort(numbers); System.out.println("Sorted List: " + numbers); > >
The above code creates a list of integers, adds four numbers to it, sorts the list, and then prints the sorted list to the console.
It uses classes from the Java standard library, including java.util.Collections , java.util.List , and java.util.ArrayList to perform the operations.
The output of the above code is shown below:
//Output Sorted List: [1, 2, 3, 4]
You can also sort a list of custom objects using the Collections.sort() method. To do this, you will need to create a comparator and pass it as an argument to the Collections.sort() method.
A comparator is an object that implements the java.util.Comparator interface. It has a single method called compare() that compares two objects and returns an integer indicating their relative order.
Here is an example of how to use a comparator to sort a list of custom objects:
import java.util.Collections; import java.util.List; import java.util.ArrayList; public class Main < public static void main(String[] args) < Listpeople = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Charlie", 20)); Collections.sort(people, new PersonComparator()); System.out.println("Sorted List: " + people); > > class Person < private String name; private int age; public Person(String name, int age) < this.name = name; this.age = age; >public String getName() < return name; >public int getAge() < return age; >@Override public String toString() < return name + " (" + age + ")"; >> class PersonComparator implements java.util.Comparator < @Override public int compare(Person a, Person b) < return a.getAge() - b.getAge(); >>
The code above creates a list of ‘Person’ objects, adds several Person objects to the list, sorts the list using a custom comparator ( PersonComparator ), and then prints out the sorted list.
The Person class has two fields, name and age , and getter methods for these fields. The PersonComparator class implements the Comparator interface and overrides the compare method to sort Person objects by age.
The output of this program will be the following:
//output Sorted List: [Charlie (20), Alice (25), Bob (30)]
It’s best to use the Collections.sort() method when you have a collection of objects that need to be sorted based on one or more fields.
For example, if you have a collection of Employee objects and you want to sort them by their last name, you can use the Collections.sort() method and pass in a custom Comparator that compares the last names of the Employee objects.
How to Use the List.Sort() Method in Java
This method sorts a list in ascending order. Here’s how it works:
import java.util.Arrays; import java.util.List; public class Main < public static void main(String[] args) < Listnumbers = Arrays.asList(5, 3, 2, 4, 1); numbers.sort(null); System.out.println(numbers); // prints [1, 2, 3, 4, 5] > >
Inside the main method above, a list of integers called «numbers» is created using the Arrays.asList method. The code then sorts this list of numbers using the default sorting method since null is passed to the sort method.
Finally, the sorted list is printed to the console using the System.out.println method, which will output «[1, 2, 3, 4, 5]».
List.sort() is useful when you have a list of elements that need to be sorted. For example, if you have a list of strings and you want to sort them in alphabetical order, you can use the List.sort() method.
List.sort() is an instance method of the List class and it sorts the elements in the order defined by their natural ordering or by a specified Icomparer implementation.
How to Use the stream.sorted() Method in Java
In Java 8 and above, you can use the Stream API to sort a list. The Stream API provides a sorted method that you can use to sort the elements of a stream.
Here is an example of how to sort a list of integers using a stream:
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main < public static void main(String[] args) < Listnumbers = Arrays.asList(5, 3, 2, 4, 1); List sortedList = numbers.stream().sorted().collect(Collectors.toList()); System.out.println(sortedList); // prints [1, 2, 3, 4, 5] > >
In the example above, the number list is converted to a stream using the stream() method. The sorted() method is then called on the stream to sort the elements. The collect(Collectors.toList()) method is used to collect the sorted elements back into a list. The result is a new list containing the sorted elements. The output will be «[1, 2, 3, 4, 5]».
stream.sorted() is best used when you have a stream of elements that need to be sorted. For example, if you have a stream of integers and you want to sort them in ascending order, you can use the stream.Sorted() method.
Conclusion
In this tutorial, you learned that there are several ways to sort a list in Java – the Collections.sort() method, the stream.sorted() method, and the List.sort() method. The best method to use depends on the specific requirements of the task at hand as we discussed above.
I hope this article has given you the correct information on how to sort a list in Java.
Sorted List Java Example
In this article, we will create a Java example on Sorted List. I will show how to sort a java.util.List using methods of java.util.Collections class.
1. SimpleSortExample
Firstly I filled the list with random values, using (int) (Math.random() * 100) to get integers between 0 and 100. Then, I print the unsorted and then the sorted version of this list, using Collections.sort() . This is my output:
2. SortWithComparatorExample
There is another way of using Collections.sort method, by passing a Comparator as a parameter. SortWithComparatorExample shows this: SortWithComparatorExample.java
I added a second parameter to Collections.sort method in order to tell that method how to sort the list. This is performed by @Overriding the compare method of the Comparator. My Comparator tells to the method that it should sort the list in the reversed order. My output is this:
3. ReverseSortExample
There is a simpler way to sort a list in the reversed order. Instead of creating your own Comparator , Java gives you a pre-defined Comparator that you can pass as the second parameter of Collections.sort method. Check out the code below: ReverseSortExample.java
Instead of creating a new Comparator , I used Collections.reverseOrder() . This pre-defined Comparator does “the heavy work” of defining your own Comparator. The output is the same as the previous example:
4. Sort objects
Let us look at an example to sort objects. We defined a class Person as below. It implements Comparable and overrides the compareTo method. Person.java
public class Person implements Comparable < private String name; private int age; public Person(String strName, int iAge)< this.name = strName; this.age = iAge; >public String getName() < return name; >public int getAge() < return age; >public void setName(String strName) < this.name = strName; >public void setAge(int iAge) < this.age = iAge; >public String toString() < return this.name; >// Compare method public int compareTo(Object obj) < return this.getName().compareTo(((Person) obj).getName()); >>
import java.util.ArrayList; import java.util.List; import java.util.Collections; public class SortedExample < public static void main(String args[])< Person p1 = new Person("Jack",30); Person p2 = new Person("Donald",29); Person p3 = new Person("Alvin",31); List personCollection = new ArrayList(); personCollection.add(p1); personCollection.add(p2); personCollection.add(p3); System.out.println("Before Sort :"+personCollection); // Using Collections Collections.sort(personCollection); System.out.println("After Sort :"+personCollection); >>
As you would notice, the above code would sort the objects based on the logic mentioned in compareTo method in Person class. The output would be as shown below:
Before Sort :[Jack, Donald, Alvin] After Sort :[Alvin, Donald, Jack]
5. Array.sort() vs Collection.sort()
- Array.sort() sorts the specified array of objects into ascending order, according to the natural ordering of elements
- All elements must implement the Comparable interface and must be mutually comparable.
- The sort is guaranteed to be stable (i.e. equal elements will not be reordered as a result of this sort)
- The implementation is stable, adaptive, iterative mergesort that requires far fewer than O(nlog(n)) comparisons when the input array is partially sorted. It takes n comparisons for an input array that is nearly ordered.
- Uses dual-pivot Quicksort algorithm for primitive arrays.
- Collections.sort() sorts the specified list into ascending order, according to the natural ordering of elements
- All elements in the list must implement the Comparable interface and must be mutually comparable.
- The sort is guaranteed to be stable
6. Download the Source Code
Last updated on Jul. 20th, 2020
How to Sort a List in Java
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Sometimes we have to sort a list in Java before processing its elements. In this tutorial, we will learn how to sort a list in the natural order. We will also learn how to use our own Comparator implementation to sort a list of objects. Java List is similar to arrays except that the length of the list is dynamic and it comes in Java Collection framework. Actually, List is an interface and most of the time we use one of its implementation like ArrayList or LinkedList etc.
Java Sort List
Here we will learn how to sort a list of Objects in Java. We can use Collections.sort() method to sort a list in the natural ascending order. All the elements in the list must implement Comparable interface, otherwise IllegalArgumentException is thrown. Let’s look at a quick example to sort a list of strings.
package com.journaldev.sort; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class JavaListSort < /** * This class shows how to sort ArrayList in java * @param args */ public static void main(String[] args) < ListstrList = new ArrayList(); strList.add("A"); strList.add("C"); strList.add("B"); strList.add("Z"); strList.add("E"); //using Collections.sort() to sort ArrayList Collections.sort(strList); for(String str: strList) System.out.print(" "+str); > >
As you can see that we are using Collections.sort() method to sort the list of Strings. The String class implements Comparable interface. Output:
Java Sort List of Objects
Let’s see another example where we will sort a list of custom objects. Note that the class must implement Comparable interface.
package com.journaldev.sort; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class JavaSortListObject < public static void main(String[] args) < Listdl = new ArrayList<>(); dl.add(new Data(2)); dl.add(new Data(3)); dl.add(new Data(1)); System.out.println("Original List::"+dl); Collections.sort(dl); System.out.println("Naturally Sorted List::"+dl); > > class Data implements Comparable < private int id; public Data(int i) < this.id = i; >@Override public int compareTo(Data d) < return this.id - d.getId(); >public int getId() < return id; >@Override public String toString() < return "Data"; > >
Original List::[Data, Data, Data] Naturally Sorted List::[Data, Data, Data]
Sort a List in Java using Comparator
Collections.sort() method is overloaded and we can also provide our own Comparator implementation for sorting rules. Since Comparator is a functional interface, we can use lambda expressions to write its implementation in a single line.
Collections.sort(dl, (d1, d2) -> < return d2.getId() - d1.getId(); >); System.out.println("Reverse Sorted List using Comparator::" + dl);
Output:
Summary
Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules. You can checkout more examples from our GitHub Repository. Reference: API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us