What are the most useful methods of the Collections utility class?

java.util.Collections is a class of static helper methods for working with collections: sorting, searching, reversing, shuffling, finding min and max, counting, creating unmodifiable or synchronized wrappers, and creating empty or single-element collections.

Key Points: • sort(list) and sort(list, comparator); binarySearch(list, key) on a sorted list. • reverse(), shuffle(), swap(), rotate() and fill() change a list in place. • max(), min() and frequency(collection, element). • unmodifiableList/Set/Map() create read-only views; synchronizedList/Set/Map() create thread-safe wrappers. • emptyList(), singletonList() and nCopies() create small fixed collections. • disjoint(c1, c2) tells you whether two collections have no elements in common. • Don't confuse it with Collection (the interface) or Arrays (helpers for arrays).

Code Example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsUtility {

    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(40, 10, 30, 20, 10));

        Collections.sort(nums);
        System.out.println("Sorted: " + nums);
        System.out.println("binarySearch(30): index " + Collections.binarySearch(nums, 30));
        System.out.println("Max: " + Collections.max(nums) + ", Min: " + Collections.min(nums));
        System.out.println("Frequency of 10: " + Collections.frequency(nums, 10));

        Collections.reverse(nums);
        System.out.println("Reversed: " + nums);
        Collections.rotate(nums, 1);
        System.out.println("Rotated by 1: " + nums);

        System.out.println("nCopies: " + Collections.nCopies(3, "Hi"));
        System.out.println("Disjoint: " + Collections.disjoint(nums, List.of(1, 2, 3)));
    }
}

Output:

Sorted: [10, 10, 20, 30, 40] binarySearch(30): index 3 Max: 40, Min: 10 Frequency of 10: 2 Reversed: [40, 30, 20, 10, 10] Rotated by 1: [10, 40, 30, 20, 10] nCopies: [Hi, Hi, Hi] Disjoint: true

Good to Know: binarySearch() only works on a list sorted in the same order, and it returns a negative number when the element is missing: -(insertion point) - 1. Interviewers sometimes ask what it returns for a missing value.

Interview Tip: A concise interview answer is:

"Collections is a utility class of static methods: sort and binarySearch, reverse, shuffle and rotate, max, min and frequency, plus wrappers like unmodifiableList and synchronizedMap, and factories like emptyList and nCopies. It's different from the Collection interface and from Arrays, which has the same kind of helpers for arrays."

Previous question: How do you sort a list of objects by multiple fields using Comparator?

Next question: Which Map methods added in Java 8 should every developer know?

More Java Collections interview questions

All Java Collections questions