Skip to lesson

The Collections utility class

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.

Java
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 Collections

Most 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.

Methods like 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

ReorderDemo.javaJava
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);    }}
Output
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 names in 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?

List<String> cart = new ArrayList<>(List.of("Laptop", "Mouse", "Cable", "Monitor"));
Collections.rotate(cart, 1);
System.out.println(cart);

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

CricketStatsDemo.javaJava
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() + ")");    }}
Output
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, min and frequency work on any collection, even the read-only List.of, because they only read.
  • With a Comparator, the same max answers different questions: most runs, or best strike rate.

Example 3 · Common mistake: max on an empty list

EmptyMaxDemo.javaJava
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);    }}
Sample output
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.max asks the list for its first item. There is none, so it throws NoSuchElementException. Line numbers inside java.base differ between Java versions.
  • The fix: check submittedMarks.isEmpty() first, and call Collections.max only 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 3
max 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.

The original ArrayList holds A, B, and then C is added, so it is A, B, C. Collections.unmodifiableList(original) is a read-only window on the same list, so it shows A, B, C. List.copyOf(original), taken before C was added, is a separate list and still shows A, B.

Example 4 · Building lists quickly

BuildListsDemo.javaJava
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());    }}
Output
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

  • nCopies builds the starting attendance; wrapping it in new ArrayList<>(...) makes it changeable.
  • toppers returns the shared Collections.emptyList() when nobody qualifies, so the caller gets an empty list, never null.

Example 5 · An unmodifiable view versus a copy

ViewVsCopyDemo.javaJava
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());        }    }}
Output
View: [Aditya, Farhan, Lakshmi]
Copy: [Aditya, Farhan]
Cannot change the view: UnsupportedOperationException

What this code does

  • Both lists were taken before Lakshmi was admitted. The view shows her; the copy does not.
  • Callers cannot add through the view, but the Hostel class can still change its own list. This is how a class shares its data safely.

Example 6 · Full example: an exam seating plan

SeatingPlanDemo.javaJava
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);    }}
Output
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 subList copies split it into halls, and disjoint confirms no student sits in both.
  • rotate shifts the seats for day 2, and min and max on Strings 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 to list.
  • List.copyOf(list): read-only copy, frozen at the moment you made it.
  • Both throw UnsupportedOperationException on add, remove or set.
  • Neither one freezes the objects inside; a Student in the list can still change.

Next step

Check your understanding

12 quick questions