Sorting in Java

Learn to sort a Set, List and Map of primitive types and custom objects in Java 7 and Java 8. We will learn to sort in ascending and descending order as well.

//Sorting an array
Arrays.sort( arrayOfItems );  
Arrays.sort( arrayOfItems, Collections.reverseOrder() );  
Arrays.sort(arrayOfItems, 2, 6);
Arrays.parallelSort(arrayOfItems);

//Sorting a List
Collections.sort(numbersList);
Collections.sort(numbersList, Collections.reverseOrder());

//Sorting a Set
Set to List -> Sort -> List to Set
Collections.sort(numbersList);

//Sorting a Map
TreeMap<Integer, String> treeMap = new TreeMap<>(map);

unsortedeMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue())
    .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

//Java 8 Lambda
Comparator<Employee> nameSorter = (a, b) -> a.getName().compareToIgnoreCase(b.getName());
Collections.sort(list, nameSorter);

Collections.sort(list, Comparator.comparing(Employee::getName));

//Group By Sorting
Collections.sort(list, Comparator
                        .comparing(Employee::getName)
                        .thenComparing(Employee::getDob));

1. Sorting an Array

Use java.util.Arrays.sort() method to sort a given array in variety of ways.

1.1. Sort array in ascending order

Java program to sort an array of integers in ascending order using Arrays.sort() method.

//Unsorted array
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 520, 1123, 366, 420 };

//Sort the array
Arrays.sort(numbers);

//Print array to confirm
System.out.println(Arrays.toString(numbers));

Program output.

[9, 11, 15, 18, 47, 55, 366, 420, 520, 1123]

1.2. Sort array in descending order

Java provides Collections.reverseOrder() comparator to reverse the default sorting behavior in one line. Use this to sort an array in descending order.

//Unsorted array
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 520, 1123, 366, 420 };

//Sort the array in reverse order
Arrays.sort(numbers, Collections.reverseOrder());

//Print array to confirm
System.out.println(Arrays.toString(numbers));

Program output.

[1123, 520, 420, 366, 55, 47, 18, 15, 11, 9]

1.3. Sorting a given array range

Arrays.sort() method is overloaded method and takes two additional parameters i.e. fromIndex (inclusive) and toIndex (exclusive).

When provided, array will be sorted within provided range from position fromIndex to position toIndex.

Given example sort the array from element 9 to 18. i.e. {9, 55, 47, 18} will be sorted and the rest elements will not be touched.

//Unsorted array
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 };

//Sort the array
Arrays.sort(numbers, 2, 6);

//Print array to confirm
System.out.println(Arrays.toString(numbers));

Program output.

[15, 11, 9, 18, 47, 55, 1123, 520, 366, 420]

1.4. Java 8 parallel sorting

Java 8 introduced lots of new APIs for parallel processing data sets and streams. One such API is Arrays.parallelSort().

The parallelSort() method breaks the array into multiple sub-arrays and each sub-array is sorted with Arrays.sort() in different threads. Finally, all sorted sub-arrays are merged into one sorted array.

The output of the parallelSort() and sort(), both APIs, will be same at last. It’s just a matter of leveraging the Java concurrency.

//Parallel sort complete array
Arrays.parallelSort(numbers);

//Parallel sort array range
Arrays.parallelSort(numbers, 2, 6);

//Parallel sort array in reverse order
Arrays.parallelSort(numbers, Collections.reverseOrder());

2. Sorting a List

Use Collections.sort() API for sorting a List in Java 7. This API uses a modified mergesort and offers guaranteed n log(n) performance.

2.1. Sort List in ascending order

//Unsorted list
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 };
List<Integer> numbersList = Arrays.asList(numbers);

//Sort the list
Collections.sort(numbersList);

//Print list to confirm
System.out.println(numbersList);

Program output.

[9, 11, 15, 18, 47, 55, 366, 420, 520, 1123]

2.2. Sort List in descending order

Similar to arrays, use Collections.reverseOrder() to reverse the default sorting behavior.

//Unsorted list
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 };
List<Integer> numbersList = Arrays.asList(numbers);

//Sort the list
Collections.sort(numbersList, Collections.reverseOrder());

//Print list to confirm
System.out.println(numbersList);

Program output.

[1123, 520, 420, 366, 55, 47, 18, 15, 11, 9]

3. Sorting a Set

There is no direct support for sorting the Set in Java. To sort a Set, follow these steps:

  1. Convert Set to List.
  2. Sort List using Collections.sort() API.
  3. Convert List back to Set.
//Unsorted list
HashSet<Integer> numbersSet = new LinkedHashSet<>( 
        Arrays.asList(15, 11, 9, 55, 47, 18, 1123, 520, 366, 420) );

List<Integer> numbersList = new ArrayList<Integer>(numbersSet) ;        //set -> list

//Sort the list
Collections.sort(numbersList);

numbersSet = new LinkedHashSet<>(numbersList);          //list -> set

//Print set to confirm
System.out.println(numbersSet);

Program output.

[9, 11, 15, 18, 47, 55, 366, 420, 520, 1123]

4. Sorting a Map

A Map is the collection of key-value pairs. So logically, we can sort the maps in two ways i.e. sort by key or sort by value.

4.1. Sort a Map by Key

The best and most effective a sort a map by keys is to add all map entries in TreeMap object. TreeMap stores the keys in sorted order, always.

HashMap<Integer, String> map = new HashMap<>();
        
map.put(50, "Alex");
map.put(20, "Charles");
map.put(60, "Brian");
map.put(70, "Edwin");
map.put(120, "George");
map.put(10, "David");

TreeMap<Integer, String> treeMap = new TreeMap<>(map);

System.out.println(treeMap);

Program output.

{10=David, 20=Charles, 50=Alex, 60=Brian, 70=Edwin, 120=George}

4.2. Sort a Map by Value

In Java 8, Map.Entry class has static method comparingByValue() to help us in sorting the Map by values.

The comparingByValue() method returns a Comparator that compares Map.Entry in natural order on values.

HashMap<Integer, String> unSortedMap = new HashMap<>();
        
unSortedMap.put(50, "Alex");
unSortedMap.put(20, "Charles");
unSortedMap.put(60, "Brian");
unSortedMap.put(70, "Edwin");
unSortedMap.put(120, "George");
unSortedMap.put(10, "David");

//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<Integer, String> sortedMap = new LinkedHashMap<>();

unSortedMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue())
    .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

System.out.println(sortedMap);

Program output.

{50=Alex, 60=Brian, 20=Charles, 10=David, 70=Edwin, 120=George}

5. Sorting Custom Objects

Custom objects are user defined classes which store the domain data e.g. Employee, Department, Account etc.

To sort a list of custom objects, we have two popular approaches i.e. Comparable and Comparator interfaces. In given examples, we will sort a collection of Employee objects.

 
import java.time.LocalDate;

public class Employee implements Comparable<Employee> {

    private Long id;
    private String name;
    private LocalDate dob;

    public Employee(Long id, String name, LocalDate dob) {
        super();
        this.id = id;
        this.name = name;
        this.dob = dob;
    }
    
    @Override
    public int compareTo(Employee o) {
        return this.getId().compareTo(o.getId());
    }

    //Getters and Setters shall be added here

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
    }
}

5.1. Comparable interface

Comparable interface enables the natural ordering of the classes it implements. It makes the classes comparable to it’s other instances.

A class implementing Comparable interface must override compareTo() method in which it can specify the comparison logic between two instances of same class.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort() and Arrays.sort().

Objects that implement this interface will be automatically sorted when put in a sorted map (as keys) or sorted set (as elements).

It is strongly recommended (though not required) that natural orderings be consistent with equals() method. Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals().

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21)));
list.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22)));
list.add(new Employee(3l, "Piyush", LocalDate.of(2018, Month.APRIL, 25)));
list.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23)));
list.add(new Employee(2l, "Pawan", LocalDate.of(2018, Month.APRIL, 24)));

Collections.sort(list);

System.out.println(list);

Program output.

[Employee [id=1, name=Alex, dob=2018-04-21], ]
Employee [id=2, name=Pawan, dob=2018-04-24], 
Employee [id=3, name=Piyush, dob=2018-04-25], 
Employee [id=4, name=Brian, dob=2018-04-22], 
Employee [id=5, name=Charles, dob=2018-04-23]]

5.2. Comparator

Many times we face situations where we do not seek natural ordering or source code unavailability for editing due to legacy code issues. In this case, we can take help of Comparator interface.

Comparator does not require modifying the source code of the class. We can create the comparison logic in separate class which implement Comparator interface and override it’s compare() method. Then pass this comparator to sort() methods along with list of custom objects.

For example, below Comparator sorts the employees list by their name.

import java.util.Comparator;

public class NameSorter implements Comparator<Employee>
{
    @Override
    public int compare(Employee e1, Employee e2) 
    {
        return e1.getName().compareToIgnoreCase( e2.getName() );
    }
}

Java program to sort a list using Comparator interface implemetation. Notice the use of NameSorter in sort() method as second argument.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21)));
list.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22)));
list.add(new Employee(3l, "Piyush", LocalDate.of(2018, Month.APRIL, 25)));
list.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23)));
list.add(new Employee(2l, "Pawan", LocalDate.of(2018, Month.APRIL, 24)));

Collections.sort(list, new NameSorter());

System.out.println(list);

Program output.

[Employee [id=1, name=Alex, dob=2018-04-21], 
Employee [id=4, name=Brian, dob=2018-04-22], 
Employee [id=5, name=Charles, dob=2018-04-23], 
Employee [id=2, name=Pawan, dob=2018-04-24], 
Employee [id=3, name=Piyush, dob=2018-04-25]]

5.3. Sort with Java 8 Lambda

Java 8 Lambda expressions help in writing Comparator implementations on the fly. We do not need to create seperate class to provide the one time comparison logic.

Comparator<Employee> nameSorter = (a, b) -> a.getName().compareToIgnoreCase(b.getName());
        
Collections.sort(list, nameSorter);

5.4. Group by sorting

To sort a collection of objects on different fields (groupby sort) using multiple comparators in chain. This chaining of comparators can be created using Comparator.comparing() and Comparator.thenComparing() methods.

For example, we sorting the list of employees by name and then sort again by their age.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21)));
list.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 01)));
list.add(new Employee(3l, "Alex", LocalDate.of(2018, Month.APRIL, 25)));
list.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23)));
list.add(new Employee(2l, "Alex", LocalDate.of(2018, Month.APRIL, 30)));

Collections.sort(list, Comparator
                        .comparing(Employee::getName)
                        .thenComparing(Employee::getDob));

System.out.println(list);

Program output.

[Employee [id=1, name=Alex, dob=2018-04-21], 
Employee [id=3, name=Alex, dob=2018-04-25], 
Employee [id=2, name=Alex, dob=2018-04-30], 
Employee [id=4, name=Brian, dob=2018-04-01], 
Employee [id=5, name=Charles, dob=2018-04-23]]

6. Summary

In the above-given examples, we learned to sort an array, list, map, and set. We saw different ways to initialize and use Comparator interface including lambda expressions.

Feel free to share your thoughts on Sorting in Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.