Sorting Collections in Java

Naveen AnamaneniUpdated · 4 min read

Sorting means arranging elements in a particular order, such as numbers from smallest to largest or names alphabetically. Java provides ready-made methods for sorting lists, arrays, sets and maps, so you never have to write a sorting algorithm yourself. Every sort uses either the natural order (Comparable) or a custom order (Comparator). In this lesson, you will learn which method to use for each kind of collection.

Ways to Sort

What to sortHowChanges the original?
A ListCollections.sort(list) or list.sort(comparator)Yes
An arrayArrays.sort(array)Yes
A SetCopy into a TreeSet, or into a list and sortNo
A Map by keyCopy into a TreeMapNo
A Map by valueSort its entries with a comparatorNo
Anything, as a new liststream().sorted().toList()No

Example: Sorting a List and an Array

Let's see an example of the two most common sorts.

SortBasics.java▶ Try it
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
public class SortBasics {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(
            List.of("Srihitha", "Navika", "Advitha"));
        Collections.sort(names);
        System.out.println("List ascending:  " + names);
        names.sort(Comparator.reverseOrder());
        System.out.println("List descending: " + names);
 
        int[] marks = {91, 78, 85, 60};
        Arrays.sort(marks);
        System.out.println("Array ascending: " + Arrays.toString(marks));
 
        Integer[] boxed = {91, 78, 85, 60};
        Arrays.sort(boxed, Collections.reverseOrder());
        System.out.println("Array descending: " + Arrays.toString(boxed));
    }
}
Output
List ascending:  [Advitha, Navika, Srihitha]
List descending: [Srihitha, Navika, Advitha]
Array ascending: [60, 78, 85, 91]
Array descending: [91, 85, 78, 60]

Explanation: Collections.sort and list.sort sort the list in place. Arrays.sort sorts an array in place. Sorting an int[] in descending order with a comparator isn't possible, because comparators work only with objects, so the descending example uses Integer[].

Example: Sorting a Set and a Map

SortSetMap.java▶ Try it
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
 
public class SortSetMap {
    public static void main(String[] args) {
        Set<String> cities = new HashSet<>(Set.of("Pune", "Delhi", "Agra"));
        System.out.println("Sorted set: " + new TreeSet<>(cities));
 
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Srihitha", 78);
        marks.put("Navika", 91);
        marks.put("Advitha", 85);
        System.out.println("By key:   " + new TreeMap<>(marks));
 
        String byValue = marks.entrySet().stream()
             .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
             .map(e -> e.getKey() + "=" + e.getValue())
             .collect(Collectors.joining(" "));
        System.out.println("By value: " + byValue);
    }
}
Output
Sorted set: [Agra, Delhi, Pune]
By key:   {Advitha=85, Navika=91, Srihitha=78}
By value: Navika=91 Advitha=85 Srihitha=78

Explanation: A HashSet has no order, so copying it into a TreeSet sorts it. Copying a map into a TreeMap sorts it by key. To sort by value, the entries are streamed, sorted with Map.Entry.comparingByValue, and joined into one string.

Is Java's Sort Stable?

Sorting objects in Java is stable: elements that compare as equal keep their original relative order. This is why sorting by name first and then by marks leaves students with equal marks in name order. (Sorting primitive arrays doesn't need to be stable, because equal numbers are indistinguishable.)

Common Mistakes

Calling Collections.sort on an unmodifiable list such as List.of(...). It throws UnsupportedOperationException; copy it into an ArrayList first.

Trying to sort a HashSet in place. Sets have no positions; use a TreeSet or a sorted list.

Passing a comparator to Arrays.sort for an int[]. Comparators need an object array such as Integer[].

Practice

  1. Easy: Sort an array of five double prices and print the cheapest and the most expensive.
  2. Harder: Given a map of subject to marks, print the subjects sorted by marks from highest to lowest, with ties sorted by subject name.

Quick check: Sorting collections

4 questions
1Which method sorts an array?
2How do you get a sorted view of a HashSet's elements?
3What does stream().sorted().toList() do to the original list?
4Is sorting objects in Java stable?

Key Takeaways

Was this tutorial helpful?

Lesson 271 of 482