Sorting Collections in Java
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 sort | How | Changes the original? |
|---|---|---|
A List | Collections.sort(list) or list.sort(comparator) | Yes |
| An array | Arrays.sort(array) | Yes |
A Set | Copy into a TreeSet, or into a list and sort | No |
A Map by key | Copy into a TreeMap | No |
A Map by value | Sort its entries with a comparator | No |
| Anything, as a new list | stream().sorted().toList() | No |
Example: Sorting a List and an Array
Let's see an example of the two most common sorts.
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));
}
}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
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);
}
}Sorted set: [Agra, Delhi, Pune]
By key: {Advitha=85, Navika=91, Srihitha=78}
By value: Navika=91 Advitha=85 Srihitha=78Explanation: 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
- Easy: Sort an array of five
doubleprices and print the cheapest and the most expensive. - Harder: Given a map of subject to marks, print the subjects sorted by marks from highest to lowest, with ties sorted by subject name.
Key Takeaways
Was this tutorial helpful?