The Collections utility class
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)You need to sort a list of marks, find the highest, or make a list read-only. Writing each of these by hand every time is a waste.
Collection or Collections?
The Collections utility class (java.util.Collections) is a class with only static helper methods and a private constructor. You never create an object of it; you call its methods to sort, search, count and wrap collections.
Collection (no s) is the interface at the top of the family: List, Set and Queue extend it. Collections (with s) is a separate class of helper methods. Its constructor is private, so new Collections() does not compile, and every method is static.
List<String> names = new ArrayList<>(List.of("Ravi", "Asha", "Meena"));Collection<String> group = names; // Collection: the interfaceCollections.sort(names); // Collections: a static helper callCollections c = new Collections(); // error: Collections() has private access in CollectionsMost helpers take a List, because they need positions: sort, reverse, shuffle, swap, rotate. Some take any Collection: max, min, frequency, disjoint, addAll. A few build new lists for you: nCopies, emptyList, singletonList.
sort, reverse and shuffle change the list you pass in and return nothing (void). So write Collections.sort(names);, not names = Collections.sort(names);, which does not compile.Reordering a list
A list of names is reordered with sort, reverse, swap and rotate, then shuffled twice with the same seed. Watch how the list changes after each call.
Example 1 · Sort, reverse, swap, rotate and shuffle
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random;
public class ReorderDemo { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of("Priya", "Arjun", "Meena", "Rohan", "Kavya"));
Collections.sort(names); System.out.println("Sorted: " + names);
Collections.reverse(names); System.out.println("Reversed: " + names);
Collections.swap(names, 0, 4); System.out.println("Swapped: " + names);
Collections.rotate(names, 1); System.out.println("Rotated: " + names);
List<String> copy1 = new ArrayList<>(names); List<String> copy2 = new ArrayList<>(names); Collections.shuffle(copy1, new Random(5)); Collections.shuffle(copy2, new Random(5)); System.out.println("Shuffle 1: " + copy1); System.out.println("Shuffle 2: " + copy2); }}Sorted: [Arjun, Kavya, Meena, Priya, Rohan] Reversed: [Rohan, Priya, Meena, Kavya, Arjun] Swapped: [Arjun, Priya, Meena, Kavya, Rohan] Rotated: [Rohan, Arjun, Priya, Meena, Kavya] Shuffle 1: [Meena, Arjun, Kavya, Rohan, Priya] Shuffle 2: [Meena, Arjun, Kavya, Rohan, Priya]
What this code does
- Each call changes
namesin place.rotate(names, 1)moved the last name,Rohan, to the front. - Two copies shuffled with
new Random(5)end in the same order. The same seed always gives the same shuffle, which makes the output testable.
sort(list) puts items in natural order; sort(list, comparator) uses your order. reverse flips the list. swap(list, i, j) exchanges two positions. rotate(list, k) moves every item k places to the right, and items that fall off the end come back at the front.
shuffle(list) puts items in a random order. A shuffle with new Random(42) gives the same order on every run, because 42 is a seed: the starting number of the random generator. Tests and examples use a seed so the output can be checked; a real lucky draw uses shuffle(list) with no seed.
Predict the output
Predict the list
Work out each result in your head, then pick it.
Round 1 of 3
What does the last line print?
Finding and counting
The same max, min and frequency calls answer different questions about scores and batters. The third program shows what happens on an empty list.
Example 2 · Cricket stats with max, min and frequency
import java.util.Collections;import java.util.Comparator;import java.util.List;
record Batter(String name, int runs, int balls) { double strikeRate() { return runs * 100.0 / balls; }}
public class CricketStatsDemo { public static void main(String[] args) { List<Integer> innings = List.of(45, 0, 102, 12, 0, 77, 102, 8);
System.out.println("Highest score: " + Collections.max(innings)); System.out.println("Lowest score: " + Collections.min(innings)); System.out.println("Ducks (0): " + Collections.frequency(innings, 0)); System.out.println("Scores of 102: " + Collections.frequency(innings, 102));
List<Batter> team = List.of( new Batter("Rohit", 64, 40), new Batter("Shubman", 88, 64), new Batter("Surya", 51, 25), new Batter("Hardik", 30, 24));
Batter topScorer = Collections.max(team, Comparator.comparingInt(b -> b.runs())); Batter fastest = Collections.max(team, Comparator.comparingDouble(b -> b.strikeRate())); Batter slowest = Collections.min(team, Comparator.comparingDouble(b -> b.strikeRate()));
System.out.println("Top scorer: " + topScorer.name() + " (" + topScorer.runs() + ")"); System.out.println("Fastest: " + fastest.name() + " (SR " + fastest.strikeRate() + ")"); System.out.println("Slowest: " + slowest.name() + " (SR " + slowest.strikeRate() + ")"); }}Highest score: 102 Lowest score: 0 Ducks (0): 2 Scores of 102: 2 Top scorer: Shubman (88) Fastest: Surya (SR 204.0) Slowest: Hardik (SR 125.0)
What this code does
max,minandfrequencywork on any collection, even the read-onlyList.of, because they only read.- With a
Comparator, the samemaxanswers different questions: most runs, or best strike rate.
Example 3 · Common mistake: max on an empty list
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class EmptyMaxDemo { public static void main(String[] args) { List<Integer> submittedMarks = new ArrayList<>(); System.out.println("Submissions: " + submittedMarks.size()); int best = Collections.max(submittedMarks); System.out.println("Best: " + best); }}Submissions: 0 Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970) at java.base/java.util.Collections.max(Collections.java:674) at EmptyMaxDemo.main(EmptyMaxDemo.java:9)
What this code does
Collections.maxasks the list for its first item. There is none, so it throwsNoSuchElementException. Line numbers insidejava.basediffer between Java versions.- The fix: check
submittedMarks.isEmpty()first, and callCollections.maxonly when the list has items.
max(c) and min(c) walk through the whole collection once and return the largest or smallest item by natural order. Pass a Comparator to use your own rule, such as "highest strike rate". When two items tie, max and min return the one they met first.
frequency(c, x) counts how many items are equal to x, using equals(). disjoint(a, b) returns true when the two collections have no item in common.
Find the bug
Find the Collections bug
Select the line that is wrong.
Print the highest order amount. The list can be empty on a quiet day.
Round 1 of 3max and min throw NoSuchElementException on an empty collection. Check isEmpty() first when the list can be empty.Building lists and read-only wrappers
An unmodifiable view is a read-only window onto another collection. Callers cannot change it, but when the original collection changes, the view shows the change.
These programs build lists with nCopies, addAll and emptyList. Then a Hostel class hands out a view and a copy of its residents, and a seating plan uses the helpers together.
Example 4 · Building lists quickly
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class BuildListsDemo { static List<String> toppers(List<String> names, List<Integer> marks) { List<String> result = new ArrayList<>(); for (int i = 0; i < names.size(); i++) { if (marks.get(i) >= 95) { result.add(names.get(i)); } } if (result.isEmpty()) { return Collections.emptyList(); } return result; }
public static void main(String[] args) { List<String> attendance = new ArrayList<>(Collections.nCopies(5, "Absent")); attendance.set(0, "Present"); attendance.set(3, "Present"); System.out.println("Attendance: " + attendance);
Collections.fill(attendance, "Holiday"); System.out.println("After fill: " + attendance);
List<String> cart = new ArrayList<>(); Collections.addAll(cart, "Laptop", "Mouse", "Keyboard"); System.out.println("Cart items: " + cart);
List<String> monitor = Collections.singletonList("Sneha"); System.out.println("Class monitor: " + monitor);
List<String> names = List.of("Ravi", "Anu", "Kiran"); List<String> none = toppers(names, List.of(81, 74, 90)); System.out.println("Toppers: " + none + ", size " + none.size()); }}Attendance: [Present, Absent, Absent, Present, Absent] After fill: [Holiday, Holiday, Holiday, Holiday, Holiday] Cart items: [Laptop, Mouse, Keyboard] Class monitor: [Sneha] Toppers: [], size 0
What this code does
nCopiesbuilds the starting attendance; wrapping it innew ArrayList<>(...)makes it changeable.toppersreturns the sharedCollections.emptyList()when nobody qualifies, so the caller gets an empty list, nevernull.
Example 5 · An unmodifiable view versus a copy
import java.util.ArrayList;import java.util.Collections;import java.util.List;
class Hostel { private final List<String> residents = new ArrayList<>();
void admit(String name) { residents.add(name); }
List<String> residentsView() { return Collections.unmodifiableList(residents); }
List<String> residentsCopy() { return List.copyOf(residents); }}
public class ViewVsCopyDemo { public static void main(String[] args) { Hostel hostel = new Hostel(); hostel.admit("Aditya"); hostel.admit("Farhan");
List<String> view = hostel.residentsView(); List<String> copy = hostel.residentsCopy();
hostel.admit("Lakshmi");
System.out.println("View: " + view); System.out.println("Copy: " + copy);
try { view.add("Intruder"); } catch (UnsupportedOperationException e) { System.out.println("Cannot change the view: " + e.getClass().getSimpleName()); } }}View: [Aditya, Farhan, Lakshmi] Copy: [Aditya, Farhan] Cannot change the view: UnsupportedOperationException
What this code does
- Both lists were taken before
Lakshmiwas admitted. The view shows her; the copy does not. - Callers cannot add through the view, but the
Hostelclass can still change its own list. This is how a class shares its data safely.
Example 6 · Full example: an exam seating plan
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random;
public class SeatingPlanDemo { public static void main(String[] args) { List<String> students = new ArrayList<>(List.of( "Aarav", "Bhavna", "Chetan", "Divya", "Eshan", "Fatima", "Gopal", "Harini"));
Collections.shuffle(students, new Random(7)); System.out.println("Random order: " + students);
List<String> hallA = new ArrayList<>(students.subList(0, 4)); List<String> hallB = new ArrayList<>(students.subList(4, 8)); System.out.println("Hall A seats: " + hallA); System.out.println("Hall B seats: " + hallB); System.out.println("No one in both halls: " + Collections.disjoint(hallA, hallB));
Collections.rotate(hallA, 1); System.out.println("Hall A, day 2: " + hallA);
List<String> sheetB = new ArrayList<>(hallB); Collections.sort(sheetB); System.out.println("Hall B attendance sheet: " + sheetB);
String first = Collections.min(students); String last = Collections.max(students); System.out.println("First and last on the roll: " + first + ", " + last); }}Random order: [Aarav, Chetan, Gopal, Bhavna, Eshan, Divya, Harini, Fatima] Hall A seats: [Aarav, Chetan, Gopal, Bhavna] Hall B seats: [Eshan, Divya, Harini, Fatima] No one in both halls: true Hall A, day 2: [Bhavna, Aarav, Chetan, Gopal] Hall B attendance sheet: [Divya, Eshan, Fatima, Harini] First and last on the roll: Aarav, Harini
What this code does
- A seeded shuffle makes a fair but repeatable order. Two
subListcopies split it into halls, anddisjointconfirms no student sits in both. rotateshifts the seats for day 2, andminandmaxonStrings give the first and last names in A to Z order.
nCopies(5, "Absent") gives a list with the same value five times. It is read-only, so copy it into an ArrayList if you want to change it. addAll(list, a, b, c) adds many values in one call, and fill(list, x) overwrites every position. emptyList() and singletonList(x) give small read-only lists with zero or one item. unmodifiableList(list) gives a view: a read-only window onto your list. Callers cannot change it, but when you change the original list, the view shows the change. List.copyOf(list) makes a separate snapshot that never changes. Pick the view when callers should see live data, and the copy when they need a fixed snapshot. For lists, sets and maps that must never change at all, the next lesson shows Immutable collections (opens in a new tab).
Collections.unmodifiableList(list): read-only view, follows later changes tolist.List.copyOf(list): read-only copy, frozen at the moment you made it.- Both throw
UnsupportedOperationExceptiononadd,removeorset. - Neither one freezes the objects inside; a
Studentin the list can still change.
Next step
Check your understanding
12 quick questions