Sub topic 8
Sorting Lists, Arrays and Streams
This chapter assumes you understand Java classes, generics, Comparable, Comparator, lists, arrays, streams, and lambda expressions. The focus is how each sorting API chooses an ordering and whether it changes the original data.
Choosing a sorting API
Java provides different methods for different data shapes:
| Data | Method | Changes the source? |
|---|---|---|
| `List` | `Collections.sort` or `List.sort` | Yes |
| Object array | `Arrays.sort` | Yes |
| Stream | `Stream.sorted` | No, it creates a sorted stream |
A sorting method uses either the element's natural ordering from Comparable or an explicitly supplied Comparator.
Sorting lists
Collections.sort(list) uses natural ordering. The element type must implement Comparable.
List.sort(comparator) accepts a custom ordering. Passing null tells it to use natural ordering.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortingDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(
Arrays.asList("Mia", "Alex", "Zoe"));
Collections.sort(names);
System.out.println(names); // [Alex, Mia, Zoe]
names.sort(Comparator.reverseOrder());
System.out.println(names); // [Zoe, Mia, Alex]
names.sort(Comparator.comparingInt(String::length));
System.out.println(names); // [Zoe, Mia, Alex]
}
}The last result has equal lengths for "Zoe", "Mia", and "Alex" only where applicable. Java's list sorting is stable: when two elements compare as equal, their original relative order is retained.
Collections.sort is useful in older code and works with any List. List.sort is more direct when you already have a list reference.
> callout note > Sorting changes the list or array passed to the method. If you need to preserve the original list, make a copy first: List<String> copy = new ArrayList<>(original);.
Sorting arrays
Use Arrays.sort for arrays. For object arrays, supply a Comparator or omit it to use natural ordering.
import java.util.Arrays;
import java.util.Comparator;
public class ArraySortingDemo {
public static void main(String[] args) {
Integer[] scores = {72, 91, 64, 88};
Arrays.sort(scores);
System.out.println(Arrays.toString(scores)); // [64, 72, 88, 91]
Arrays.sort(scores, Comparator.reverseOrder());
System.out.println(Arrays.toString(scores)); // [91, 88, 72, 64]
int[] values = {4, 1, 3, 2};
Arrays.sort(values);
System.out.println(Arrays.toString(values)); // [1, 2, 3, 4]
}
}Primitive arrays, such as int[], can use natural ascending order but cannot use a Comparator directly. Use Integer[] when a custom object ordering is required.
Sorting streams
Stream.sorted() returns a sorted stream. It does not reorder the list or array that supplied the stream.
List<String> names = Arrays.asList("Mia", "Alex", "Zoe");
List<String> result = names.stream()
.sorted(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()))
.collect(java.util.stream.Collectors.toList());
System.out.println(result); // [Mia, Zoe, Alex]
System.out.println(names); // [Mia, Alex, Zoe]A stream sort is useful when sorting is one step in a larger pipeline, such as filtering, mapping, and collecting. Remember that sorted() is a stateful operation. It must see the elements before it can emit them in order, which can require memory for the elements being sorted.
Selecting the method
Use List.sort when you need to reorder a list in place. Use Arrays.sort for an array. Use Stream.sorted when sorting belongs inside a stream pipeline or when the original source must remain unchanged.
Exercise
What happens to the original list after List<String> sorted = original.stream().sorted().collect(Collectors.toList());?
Show answer
The original list is unchanged. The sorted elements are collected into a separate list.