Learn to sort an array or a collection in Java. we will learn to sort set, list and map containing primitive types and custom objects. We will learn to sort in ascending an descending order as well.
1. Sort an Array
1.1. Sort array in ascending order
Java program to sort an array of integers in ascending order using Arrays.sort() method.
import java.util.Arrays; public class JavaSortExample { public static void main(String[] args) { //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. Sort 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 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(). It breaks the array into different sub-arrays and each sub-array is sorted with Arrays.sort()
in different threads. Finally all sorted sub-arrays are merged to one array as result.
The output of the parallelSort()
and sort(), both apis, will be same at last. It’s just a matter of leveraging multi-threading.
Arrays.parallelSort(numbers); Arrays.parallelSort(numbers, 2, 6); Arrays.parallelSort(numbers, Collections.reverseOrder());
2. Sort a List
Lists can be sorted in Java using Collections.sort() API. It 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. Sort a Set
There is no direct support for sorting the sets in Java. To sort a set, follow these steps:
- Convert set to list.
- Sort list using Collections.sort() API.
- 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. Sort a Map
A map is the collection of key-value pairs. So map can be sorted 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 store the entry sets in sorted order by keys.
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 you in sorting by values. This 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. Sort custom objects
Custom objects are user defined classes which hold the domain data e.g. Employee
, Department
, Account
etc.
To sort list of custom objects, we have two popular approaches i.e. Comparable and Comparator. In given examples, we will sort a collection of instances of Employee
class.
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 @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]"; } }
5.1. Comparable
Comparable
interface enables the natural ordering of the classes it implements. It makes the classes comparable to it’s 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
It is strongly recommended (though not required) that natural orderings be consistent with equals
. 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 situation where we do not seek natual ordering or class file unavilable for edit due to legacy code issue. In this case, we can take help of Comparator interface.
Comparator does not require to modivy the sourcecode of the class. We can create the comparison logic in seperate 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 sort 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 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 above given examples, we learned to sort 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 !!