Java Collections sort()
Learn to use Collections.sort() method to sort a list of objects using some examples.
By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections.reverseOrder() method, which returns a Comparator, for reverse sorting.
1. Sorting in Natural Order and Reverse Order
Collections.sort(list); //Sorts in natural order Collections.sort(list, Collections.reverseOrder()); //Sorts in reverse order
- Above method sorts the specified list of items into their natural order.
- All items must implement the Comparable interface.
- All items must be mutually comparable and should not throw ClassCastException .
- This sort is guaranteed to be stable. It means that equal elements will not be reordered as a result of the sort.
- The specified list must be modifiable, but need not to be resizable.
- The sort() does not return any value.
1.1. Sorting an ArrayList of Strings
Java program to sort a list of strings lexicographically (in the dictionary order).
List names = Arrays.asList("Alex", "Charles", "Brian", "David"); //Prints - [Alex, Brian, Charles, David] Collections.sort(names); //Prints - [David, Charles, Brian, Alex] Collections.sort(names, Collections.reverseOrder());
1.2. Sorting ArrayList of Objects by Field
We may require to sort a list of custom objects which can have their own sorting logic. In this case, implement the Comparator interface in the custom class.
For example, the domain object Employee has default sorting on the name field. Checkout for comparison logic in compareTo() method.
public class Employee implements Comparable < private Integer id; private String name; private String email; private LocalDate dateOfBirth; //Getters and Setters @Override public int compareTo(Employee e) < return this.getName().compareTo(e.getName()); >>
Nest Java program sorts the list of Employee objects by their name;
ArrayList employees = methodReturnsUnsortedList(); //Narutal order sorting Collections.sort(employees); //Reverse sorting Collections.sort(employees, Collections.reverseOrder());
2. Custom Sorting using Comparators
The second parameter in sort() method takes an instance of Comparator .
We can implement any kind of comparison logic with the help of comparators and then we can use sort() method to sort the list based on the given custom logic.
Collections.sort(List, Comparator);
We can create a separate Comparator instances for each kind of sorting need, and then we can combine those instances to create group sorting effect.
For example, if we want to sort the Employee list on three fields – id, name, and age. In this case, we need to create 3 Comparator instances.
2.1. Creating Custom Comparator
This is general syntax to create a Comparator in Java. In this case, we are creating a Comparator which will sort the Employee list by id field.
Comparator compareById = new Comparator() < @Override public int compare(Employee o1, Employee o2) < return o1.getId().compareTo(o2.getId()); >>; Comparator compareByName = new Comparator() < @Override public int compare(Employee o1, Employee o2) < return o1.getName().compareTo(o2.getName()); >>;
We can use lambda expression for further shortening the syntax.
//Id Comparator Comparator compareById = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() ); //Name Comparator Comparator compareByName = (Employee o1, Employee o2) -> o1.getName().compareTo( o2.getName() );
2.2. Using Comparator for Sorting
ArrayList employees = getUnsortedEmployeeList(); Comparator compareById = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() ); Collections.sort(employees, compareById); Collections.sort(employees, compareById.reversed());
In the above code examples, we learned to sort an ArrayList in default order or reverse order.
We also learned to use the Comparators for implementing the custom sorting logic.
Java Collections sort()
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.
Today we will look into Java Collections sort method. While working with Collections in java, more than often we need to sort the data.
Java Collections sort()
- sort(List list) : Sorts the elements of the List in ascending order of their natural ordering.
- sort(List list, Comparator c) : Sorts the elements of the list according to the order induced by the comparator.
Note that the above methods signature use generics but I have removed them here for simplicity in reading. Let us one by one dig into how and when we can use both these methods.
Java Collections sort(List list)
Consider an ArrayList of String :
List fruits = new ArrayList(); fruits.add("Apple"); fruits.add("Orange"); fruits.add("Banana"); fruits.add("Grape");
Now, we will sort it using Collections.sort() :
Collections.sort(fruits); // Print the sorted list System.out.println(fruits);
The output of this program will be:
[Apple, Banana, Grape, Orange]
Hence, we can see that Collections.sort() has sorted the list of String in Lexical order. And it does not return anything. What if we have a list of custom objects? Of course, we can sort them as well. Consider a class Fruit:
package com.journaldev.collections; public class Fruit < private int id; private String name; private String taste; Fruit(int id, String name, String taste)< this.id=id; this.name=name; this.taste=taste; >>
Let’s create a list of Fruits:
List fruitList=new ArrayList(); Fruit apple=new Fruit(1, "Apple", "Sweet"); Fruit orange=new Fruit(2, "Orange", "Sour"); Fruit banana=new Fruit(4, "Banana", "Sweet"); Fruit grape=new Fruit(3, "Grape", "Sweet and Sour"); fruitList.add(apple); fruitList.add(orange); fruitList.add(banana); fruitList.add(grape);
In order to sort this list, if we directly use the Collections.sort(List list) , it will give a Compile Time Error because there is no natural ordering defined for the Fruit objects. So, it doesn’t know how to sort this list. For objects to have a natural order they must implement the interface java.lang.Comparable . The Comparable interface has a method compareTo() , which returns a negative, 0, a positive if the current value is less than, equal to, or greater than the value we are comparing with, respectively. Let’s enhance the Fruit class to implement Comparable interface. We are defining that the natural order of sorting is based on the “id” field of Fruit:
package com.journaldev.collections; public class Fruit implements Comparable < private int id; private String name; private String taste; Fruit(int id, String name, String taste)< this.id=id; this.name=name; this.taste=taste; >@Override public int compareTo(Object o) < Fruit f = (Fruit) o; return this.id - f.id ; >>
Now that we have implemented Comparable , we can sort the list without any errors:
Collections.sort(fruitList); fruitList.forEach(fruit -> < System.out.println(fruit.getId() + " " + fruit.getName() + " " + fruit.getTaste()); >);
The output will be as below:
1 Apple Sweet 2 Orange Sour 3 Grape Sweet and Sour 4 Banana Sweet
Java Collections sort(List list, Comparator c)
In order to define a custom logic for sorting, which is different from the natural ordering of the elements, we can implement the java.util.Comparator interface and pass an instance of it as the second argument of sort() . Let’s consider that we want to define the ordering based on the “name” field of the Fruit. We implement the Comparator , and in its compare() method, we need to write the logic for comparison:
package com.journaldev.collections; class SortByName implements Comparator < @Override public int compare(Fruit a, Fruit b) < return a.getName().compareTo(b.getName()); >>
Now, we can sort it using this comparator:
Collections.sort(fruitList, new SortByName());
The output will be as below:
1 Apple Sweet 4 Banana Sweet 3 Grape Sweet and Sour 2 Orange Sour
Instead of writing new class for Comparator, using lambda function, we can provide sorting logic at runtime as well:
Collections.sort(fruitList, (a, b) -> < return a.getName().compareTo(b.getName()); >);
Java Collections.reverseOrder
By default, Collection.sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods:
- reverseOrder() : Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.
- reverseOrder(Comparator cmp) : Returns a Comparator that imposes reverse ordering of the specified comparator.
Here are the examples for both these methods:
Java Collections reverseOrder() example
Collections.sort(fruits, Collections.reverseOrder()); System.out.println(fruits);
It’ll output the fruits in reverse alphabetical order:
[Orange, Grape, Banana, Apple]
Java Collections reverseOrder(Comparator cmp) example
Collections.sort(fruitList, Collections.reverseOrder(new SortByName())); fruitList.forEach(fruit -> < System.out.println(fruit.getId() + " " + fruit.getName() + " " + fruit.getTaste()); >);
2 Orange Sour 3 Grape Sweet and Sour 4 Banana Sweet 1 Apple Sweet
That’s all for Java Collections sort() method and it’s examples. Reference: API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.