Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations
The algorithms in java.util.Collections and Arrays: stable sorting with comparators, shuffling, binary search and insertion points, min, max, reverse, rotate, removeIf and replaceAll, set operations with retainAll and removeAll, toArray, and writing your own generic algorithms.
kvi5hnuCode Sprout team member11 min readOn this page
Collection classes are only half of the framework. The other half is algorithms: sorting, searching, shuffling and many small utilities, written once against the collection interfaces so they work with any implementation. This article covers everything in Collections and Arrays that you're likely to need, explains why sort is stable and why binarySearch loses its speed advantage on a LinkedList, and finishes with how to design your own methods that take and return collections.
Why generic algorithms?
Finding the largest element looks different for each container. An array uses a[i], an ArrayList uses get(i), and a LinkedList needs an iterator because get(i) would be O(n). Writing and testing each variant, with all its empty-container and off-by-one cases, is tedious.
The fix is to ask: what is the weakest interface this algorithm needs? Finding a maximum only needs to visit each element once, so plain iteration over a Collection is enough:
static <T extends Comparable<? super T>> T max(Collection<? extends T> elements) {
if (elements.isEmpty()) throw new NoSuchElementException();
Iterator<? extends T> iter = elements.iterator();
T largest = iter.next();
while (iter.hasNext()) {
T next = iter.next();
if (largest.compareTo(next) < 0) largest = next;
}
return largest;
}
This one method works for lists, sets, deques, map views, and anything else that implements Collection. Arrays aren't collections, so they need their own overloads, which is why java.util.Arrays exists alongside java.util.Collections. In fact, Collections.max and Collections.min already exist, with comparator overloads. For anything more elaborate, the streams API, covered later in the course, adds a large algorithm library: coll.stream().max(comparator), filtering, grouping and so on.
Sorting
Collections.sort(list) sorts a list of Comparable elements. Since Java 8, the more direct way is the default method list.sort(comparator). Passing null as the comparator means natural order.
staff.sort(Comparator.comparingDouble(Employee::salary)); // by salary
staff.sort(Comparator.comparingDouble(Employee::salary).reversed()); // highest salary first
words.sort(Comparator.reverseOrder()); // reverse natural order
Comparator.reverseOrder() reverses the natural ordering. comparator.reversed() reverses any comparator. Combined with thenComparing, from the comparators article, you can express almost any ordering in one line.
How it works, and why stability matters
Textbook sorts index into arrays, which is a poor fit for linked lists. Java doesn't use a special linked-list merge sort. List.sort copies the elements into an array, sorts the array, and writes the result back through a list iterator. (ArrayList skips the copy and sorts its internal array directly.) The copy is O(n) extra work, which is negligible next to the O(n log n) sort.
For objects, the array sort is TimSort, a hybrid of merge sort and insertion sort. It is O(n log n) in the worst case and close to O(n) on input that is already partly sorted, which real-world data often is. Above all, it is stable: elements that compare as equal keep their relative order.
Stability lets you build up multi-key sorts. Sort employees by name, then sort by salary. Employees with the same salary are still in name order, so the result is "by salary, then by name". The demo shows this with Ali and Ben, and Mia and Zoe. With an unstable sort you would have to write the combined comparator yourself.
What kinds of list can be sorted?
Because collections may leave "optional" methods unimplemented, every algorithm documents what it needs. sort needs a modifiable list, meaning one that supports set. It doesn't need a resizable list, one that supports add and remove. So Arrays.asList(array) can be sorted, which sorts the array, but List.of(...) and Collections.unmodifiableList(...) throw UnsupportedOperationException.
Shuffling
Collections.shuffle(list) does the opposite of sorting. It randomly permutes the list using the Fisher–Yates algorithm, which produces every permutation with equal probability in O(n) time. Lists that don't implement RandomAccess are copied into an array, shuffled, and copied back.
Collections.shuffle(cards); // default randomness
Collections.shuffle(cards, new Random(42)); // reproducible (tests, simulations)
Collections.shuffle(cards, RandomGenerator.of("L64X128MixRandom")); // Java 21: any RandomGenerator
Passing a seeded generator makes a shuffle reproducible, which is invaluable in tests. The lottery example in the demo shuffles the numbers 1 to 49, takes the first six, and sorts them for display.
Binary search
If a list is sorted, you can find an element by repeatedly halving the search range. Look at the middle element, then continue in the left or right half. A list of 1,024 elements needs at most about 10 comparisons, instead of an average of 512 for a linear scan, or all 1,024 to confirm that the element is missing.
int i = Collections.binarySearch(list, key); // list sorted in natural order
int i = Collections.binarySearch(list, key, comparator); // list sorted by this comparator

A non-negative result is the index of a matching element. If several elements match, any one of them may be returned. A negative result means the key is absent, and it encodes where the key would go: insertionPoint = -i - 1. The extra -1 is there because -0 would be indistinguishable from "found at index 0". So you can keep a list sorted like this:
if (i < 0) list.add(-i - 1, key);
Arrays.binarySearch covers arrays of every primitive type and of objects, with optional fromIndex/toIndex bounds and a comparator.
Simple algorithms
Collections has many small algorithms. You could write each as a loop, but the named call says what it does. Compare
for (int i = 0; i < words.size(); i++)
if (words.get(i).equals("C++")) words.set(i, "Java");
with Collections.replaceAll(words, "C++", "Java"). The second one reads like the intention.
| Method | Effect |
|---|---|
min(c), max(c), plus comparator overloads | smallest or largest element |
reverse(list) | reverses in place: [t, a, r] becomes [r, a, t] |
rotate(list, d) | moves the element at index i to (i + d) % size: [t, a, r] rotated by 2 becomes [a, r, t] |
swap(list, i, j) | swaps two positions |
fill(list, v) | sets every position to v |
copy(dest, src) | copies src into the same positions of dest, which must be at least as long |
replaceAll(list, old, new) | replaces every element equal to old |
addAll(c, a, b, ...) | adds several values; returns whether c changed |
frequency(c, o) | how many elements equal o |
disjoint(c1, c2) | true if no element is common |
indexOfSubList(l, s), lastIndexOfSubList(l, s) | position of s inside l, or −1 |
nCopies(n, v) | immutable list of n identical elements |
Two lambda-based default methods are even more useful:
words.removeIf(w -> w.length() <= 3); // Collection.removeIf (Java 8)
words.replaceAll(String::toLowerCase); // List.replaceAll (Java 8)
Bulk operations
The bulk methods of Collection give you set algebra without loops:
var result = new HashSet<>(firstSet);
result.retainAll(secondSet); // intersection
result.removeAll(secondSet); // difference (starting from a fresh copy of firstSet)
result.addAll(secondSet); // union
first.containsAll(second); // subset test
Each starts from a copy, because retainAll and removeAll modify the receiver. Bulk operations become even more useful when you apply them to views:
staffMap.keySet().removeAll(terminatedIds); // fire employees: removes their map entries
relocated.addAll(staff.subList(0, 10)); // copy the first ten elements
staff.subList(0, 10).clear(); // and remove them from staff
Performance tip: a.removeAll(b) calls b.contains for each element of a. If b is a large List, that is O(n·m). Turn b into a HashSet first.
Converting between collections and arrays
Much of the Java API is older than the collections framework, so you still have to convert now and then.
Array to list: List.of(array) gives an immutable copy, Arrays.asList(array) gives a fixed-size view, and new ArrayList<>(Arrays.asList(array)) gives a fully mutable copy.
List to array: toArray() returns an Object[], and you can't cast it to String[]. The array's runtime type really is Object[], so the cast throws ClassCastException. Pass an array constructor instead:
String[] values = staff.toArray(String[]::new); // Java 11
String[] values = staff.toArray(new String[0]); // older form, still common
The older form allocates a new array of the right type when the one passed is too small. Passing a zero-length array is now the recommended idiom; pre-sizing with new String[staff.size()] brings no benefit on modern JVMs.
Writing your own algorithms
When you write a method that takes a collection, accept the most general interface that does the job:
- If you just iterate, take
Collection<Item>, or evenIterable<Item>, the interface that the enhancedforloop uses. - If order or positions matter, take
List<Item>. - Use wildcards for flexibility:
Collection<? extends Item>for input you only read (see the article on wildcards).
public void processItems(Collection<? extends Item> items) { // not ArrayList<Item>
for (Item item : items) ...
}
Callers can now pass an ArrayList, a HashSet, a map's values(), or List.of(array) without repackaging anything.
For return types, promise as little as possible. List<Item> is better than ArrayList<Item>, because you stay free to return List.of() for the empty case, an unmodifiable view, or a different implementation later. Older APIs such as Swing's JComboBox(Vector<?>) don't follow this rule only because they predate the collections framework.
A complete example
import java.util.*;
public class Solution {
record Employee(String name, double salary) {}
// a generic algorithm: works for any collection, needs only iteration
static <T extends Comparable<? super T>> T max(Collection<? extends T> elements) {
if (elements.isEmpty()) throw new NoSuchElementException();
Iterator<? extends T> iter = elements.iterator();
T largest = iter.next();
while (iter.hasNext()) {
T next = iter.next();
if (largest.compareTo(next) < 0) largest = next;
}
return largest;
}
public static void main(String[] args) {
// 1. one algorithm, many collections
System.out.println("max: " + max(List.of(3, 9, 4)) + " " + max(new TreeSet<>(Set.of("kiwi", "fig", "plum")))
+ " " + max(new ArrayDeque<>(List.of(2.5, 1.5))) + ", Collections.min " + Collections.min(List.of(3, 9, 4)));
// 2. sorting: natural, comparator, reversed, and stability
var staff = new ArrayList<>(List.of(
new Employee("Mia", 60_000), new Employee("Ali", 75_000), new Employee("Zoe", 60_000),
new Employee("Ben", 75_000), new Employee("Eva", 50_000)));
staff.sort(Comparator.comparing(Employee::name)); // first by name...
staff.sort(Comparator.comparingDouble(Employee::salary).reversed()); // ...then by salary, descending
staff.forEach(e -> System.out.print(e.name() + "/" + (int) e.salary() + " "));
System.out.println("(equal salaries stay in name order: stable sort)");
var words = new ArrayList<>(List.of("pear", "Apple", "fig", "banana"));
Collections.sort(words);
System.out.print("natural " + words);
words.sort(Comparator.reverseOrder());
System.out.print(", reverseOrder " + words);
words.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(", case-insensitive " + words);
try {
Collections.sort(List.of("b", "a"));
} catch (UnsupportedOperationException e) {
System.out.println("sorting an unmodifiable list: UnsupportedOperationException");
}
// 3. shuffling: a lottery draw, seeded so the output is repeatable
var numbers = new ArrayList<Integer>();
for (int i = 1; i <= 49; i++) numbers.add(i);
Collections.shuffle(numbers, new Random(2026));
List<Integer> winning = new ArrayList<>(numbers.subList(0, 6));
Collections.sort(winning);
System.out.println("winning combination " + winning);
// 4. binary search and the insertion point
var sorted = new ArrayList<>(List.of(10, 20, 30, 40, 50));
System.out.println("binarySearch(30) = " + Collections.binarySearch(sorted, 30));
int i = Collections.binarySearch(sorted, 35);
System.out.println("binarySearch(35) = " + i + " -> insert at " + (-i - 1));
if (i < 0) sorted.add(-i - 1, 35);
System.out.println("after insert " + sorted + ", Arrays.binarySearch " + Arrays.binarySearch(new int[] {1, 4, 9}, 4));
// 5. simple algorithms
var letters = new ArrayList<>(List.of("s", "t", "a", "r"));
System.out.print("indexOfSubList " + Collections.indexOfSubList(letters, List.of("t", "a", "r")));
Collections.reverse(letters);
System.out.print(", reverse " + letters);
Collections.rotate(letters, 1);
System.out.print(", rotate 1 " + letters);
Collections.swap(letters, 0, 3);
System.out.println(", swap 0 3 " + letters);
var langs = new ArrayList<>(List.of("C++", "Go", "C++", "Rust"));
Collections.replaceAll(langs, "C++", "Java");
Collections.addAll(langs, "Kotlin", "Java");
System.out.println("replaceAll/addAll " + langs + ", frequency(Java) " + Collections.frequency(langs, "Java")
+ ", disjoint with [Go] " + Collections.disjoint(langs, List.of("Go")));
var target = new ArrayList<>(Collections.nCopies(5, "-"));
Collections.copy(target, List.of("a", "b"));
System.out.print("copy " + target);
Collections.fill(target, "x");
System.out.println(", fill " + target);
// 6. removeIf and List.replaceAll
var text = new ArrayList<>(List.of("The", "Quick", "brown", "FOX", "jumps", "over"));
text.removeIf(w -> w.length() <= 3);
text.replaceAll(String::toLowerCase);
System.out.println("removeIf + replaceAll " + text);
var arrayList = new ArrayList<>(List.of("abc", "def", "ghi"));
var linkedList = new LinkedList<>(arrayList);
arrayList.removeIf(w -> w.length() == arrayList.size()); // DON'T: predicate reads the collection
linkedList.removeIf(w -> w.length() == linkedList.size());
System.out.println("predicate that reads the list: ArrayList " + arrayList + ", LinkedList " + linkedList);
// 7. bulk operations
var first = Set.of("ann", "bob", "cy", "dee");
var second = Set.of("bob", "dee", "eve");
var intersection = new TreeSet<>(first);
intersection.retainAll(second);
var difference = new TreeSet<>(first);
difference.removeAll(second);
var union = new TreeSet<>(first);
union.addAll(second);
System.out.println("intersection " + intersection + ", difference " + difference + ", union " + union);
var staffMap = new TreeMap<>(Map.of("E1", "Ann", "E2", "Bob", "E3", "Cy", "E4", "Dee"));
staffMap.keySet().removeAll(Set.of("E2", "E4"));
System.out.println("after keySet().removeAll " + staffMap);
var relocated = new ArrayList<String>();
var queue = new ArrayList<>(List.of("q1", "q2", "q3", "q4", "q5"));
relocated.addAll(queue.subList(0, 2));
queue.subList(0, 2).clear();
System.out.println("relocated " + relocated + ", remaining " + queue);
// 8. collections and arrays
String[] namesArray = {"Ann", "Bob"};
List<String> nameList = List.of(namesArray);
Object[] objects = nameList.toArray();
String[] strings = nameList.toArray(String[]::new);
System.out.println("toArray() is " + objects.getClass().getSimpleName() + ", toArray(String[]::new) is "
+ strings.getClass().getSimpleName() + " " + Arrays.toString(strings));
try {
String[] bad = (String[]) objects;
System.out.println(bad.length);
} catch (ClassCastException e) {
System.out.println("(String[]) list.toArray(): ClassCastException");
}
}
}
max: 9 plum 2.5, Collections.min 3
Ali/75000 Ben/75000 Mia/60000 Zoe/60000 Eva/50000 (equal salaries stay in name order: stable sort)
natural [Apple, banana, fig, pear], reverseOrder [pear, fig, banana, Apple], case-insensitive [Apple, banana, fig, pear]
sorting an unmodifiable list: UnsupportedOperationException
winning combination [5, 6, 15, 26, 43, 49]
binarySearch(30) = 2
binarySearch(35) = -4 -> insert at 3
after insert [10, 20, 30, 35, 40, 50], Arrays.binarySearch 1
indexOfSubList 1, reverse [r, a, t, s], rotate 1 [s, r, a, t], swap 0 3 [t, r, a, s]
replaceAll/addAll [Java, Go, Java, Rust, Kotlin, Java], frequency(Java) 3, disjoint with [Go] false
copy [a, b, -, -, -], fill [x, x, x, x, x]
removeIf + replaceAll [quick, brown, jumps, over]
predicate that reads the list: ArrayList [], LinkedList [def, ghi]
intersection [bob, dee], difference [ann, cy], union [ann, bob, cy, dee, eve]
after keySet().removeAll {E1=Ann, E3=Cy}
relocated [q1, q2], remaining [q3, q4, q5]
toArray() is Object[], toArray(String[]::new) is String[] [Ann, Bob]
(String[]) list.toArray(): ClassCastException
Common questions
Collections.sort(list) or list.sort(null)?
They do the same thing. Collections.sort simply calls list.sort. Modern code usually writes list.sort(comparator), passing null or Comparator.naturalOrder() for natural order.
Is Java's sort stable?
Yes, for objects. List.sort, Collections.sort and Arrays.sort(Object[]) use TimSort, which keeps equal elements in their original order. Primitive arrays use dual-pivot Quicksort, where stability makes no difference.
Why does binarySearch return a strange negative number?
A negative result means the key wasn't found. It encodes the insertion point as -(insertionPoint) - 1. Compute -result - 1 to get the index where you'd insert the key to keep the list sorted.
Why can't I cast list.toArray() to String[]?
toArray() with no arguments creates an array whose runtime type is Object[], and that cast fails. Call list.toArray(String[]::new) or list.toArray(new String[0]).
How do I shuffle reproducibly for a test?
Pass a seeded generator: Collections.shuffle(list, new Random(42)). The same seed gives the same permutation on every run of the same JDK. Since Java 21, shuffle also accepts a RandomGenerator.
API reference
java.util.Collections
| Method | Description |
|---|---|
static <T extends Comparable<? super T>> void sort(List<T> list) | stable sort, O(n log n) |
static void shuffle(List<?> list), shuffle(List<?> list, Random r), shuffle(List<?> list, RandomGenerator r) (Java 21) | random permutation |
static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key), binarySearch(List<? extends T> list, T key, Comparator<? super T> c) | index of the key, or -insertionPoint - 1; binary search for RandomAccess lists, otherwise iterator-based |
min, max (with optional Comparator) | smallest or largest element |
copy, fill, addAll, replaceAll, swap, reverse, rotate | simple list algorithms (see the table above) |
indexOfSubList, lastIndexOfSubList, frequency, disjoint | searching and counting |
java.util.List<E>, java.util.Collection<E>, java.util.Comparator<T>
| Method | Description |
|---|---|
default void sort(Comparator<? super E> c) (List) | sorts this list; null means natural order |
default void replaceAll(UnaryOperator<E> op) (List) | replaces each element with op(element) |
default boolean removeIf(Predicate<? super E> filter) (Collection) | removes all matching elements |
boolean removeAll(Collection<?> c), retainAll(Collection<?> c), addAll(Collection<? extends E> c), containsAll(Collection<?> c) (Collection) | bulk set operations |
<T> T[] toArray(IntFunction<T[]> generator) (Collection, Java 11) | array of the right runtime type |
static <T extends Comparable<? super T>> Comparator<T> reverseOrder() (Comparator) | reverse natural ordering |
default Comparator<T> reversed() (Comparator) | this comparator reversed |
java.util.Arrays
| Method | Description |
|---|---|
static void sort(...), static void parallelSort(...) | sort arrays: Quicksort for primitives, TimSort for objects |
static int binarySearch(T[] a, T key), binarySearch(T[] a, int from, int to, T key), comparator overloads | binary search in a sorted array, for every primitive type and Object |
Summary
- Generic algorithms are written against the weakest interface that works.
CollectionsandArrayssupply sorting, searching, shuffling and many small utilities. list.sortandCollections.sortare stable TimSorts. Stability lets you chain sorts, and the list only has to be modifiable, not resizable.binarySearchneeds a sorted, random-access list. A negative resultimeans "insert at-i - 1".- Prefer named utilities such as
replaceAll,frequencyandrotate, and the lambda methodsremoveIfandreplaceAll, over hand-written loops. KeepremoveIfpredicates free of side effects. retainAll,removeAllandaddAllgive intersection, difference and union, and they combine powerfully with views.- Convert lists to arrays with
toArray(String[]::new). Accept general interfaces as parameters and return interfaces.
Practice Questions
You sort a list of people by city, then sort it again by age. In what order are two 30-year-olds from different cities?
In city order. The sort is stable, so the second sort keeps the relative order from the first one for elements with equal age.
Collections.binarySearch returns -6. What does that mean?
The key isn't present, and its insertion point is -(-6) - 1 = 5. Inserting at index 5 keeps the list sorted.
Why does (String[]) list.toArray() throw ClassCastException even though the list holds only strings?
toArray() creates an array whose runtime type is Object[]. Casting an array object to String[] checks that runtime type, not the elements, so it fails. Use list.toArray(String[]::new).
How do you compute the elements that are in set a but not in set b, without modifying a?
var diff = new HashSet<>(a); diff.removeAll(b);. Copy first, because removeAll mutates the receiver.
A method only loops over its argument. Should its parameter be ArrayList<Item>, List<Item> or Iterable<? extends Item>?
Iterable<? extends Item>, or Collection<? extends Item> if you also need size() or isEmpty(). It accepts the widest range of arguments, including lists of Item subtypes, without making callers repackage anything.
Previous: Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views
Next: Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet
Related reading
- Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
- Java Maps: HashMap, TreeMap and Updating Map Entries
- Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue
- Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.