The Collections utility class

Collections · lesson 13 of 42 · 3 min read

Use the one-line helpers in java.util.Collections instead of hand-rolling them.

Open this lesson in the learning hub

Key points

  • Collections (plural) is a box of static helpers. Collection (singular) is the interface. Easy to mix up.
  • Ordering: sort, reverse, shuffle, swap. Seed shuffle for repeatable runs.
  • binarySearch needs a sorted list. A negative result is -(insertionPoint) - 1, so you learn where it would go.
  • Counting and comparing: frequency, disjoint, min, max, nCopies.
  • These mutate the list in place. List.sort is the modern equivalent of Collections.sort.
  • For empty results prefer List.of() over Collections.emptyList() in new code — same effect, cleaner call.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(5, 3, 9, 1, 7));

        Collections.sort(nums);
        System.out.println("sorted          : " + nums);
        System.out.println("binarySearch(7) : index " + Collections.binarySearch(nums, 7));
        System.out.println("binarySearch(4) : " + Collections.binarySearch(nums, 4) + "  (negative = not found)");
        System.out.println("min / max       : " + Collections.min(nums) + " / " + Collections.max(nums));

        Collections.reverse(nums);
        System.out.println("reverse         : " + nums);
        Collections.swap(nums, 0, 4);
        System.out.println("swap(0,4)       : " + nums);
        Collections.shuffle(nums, new Random(7));
        System.out.println("seeded shuffle  : " + nums);

        List<String> votes = List.of("yes", "no", "yes", "yes");
        System.out.println("frequency(yes)  : " + Collections.frequency(votes, "yes"));
        System.out.println("disjoint        : " + Collections.disjoint(votes, List.of("maybe")));
        System.out.println("nCopies(3,'-')  : " + Collections.nCopies(3, "-"));
        System.out.println("emptyList       : " + Collections.emptyList());
    }
}

Before writing a loop over a list, check whether Collections already did it.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.