Java Collections Utility Class: Sorting, Shuffling & Immutability

The java.util.Collections class consists exclusively of static utility methods that operate on or return collections. It provides algorithms for sorting, reversing, searching, shuffling, and creating thread-safe or immutable views.

Essential java.util.Collections Methods

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

public class CollectionsUtilityDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(45);
        numbers.add(12);
        numbers.add(89);
        numbers.add(33);

        // 1. sort() - In-place TimSort:
        Collections.sort(numbers);
        System.out.println("Sorted:   " + numbers); // [12, 33, 45, 89]

        // 2. reverse() - Inverts element order:
        Collections.reverse(numbers);
        System.out.println("Reversed: " + numbers); // [89, 45, 33, 12]

        // 3. min() and max() algorithms:
        System.out.println("Min Value: " + Collections.min(numbers)); // 12
        System.out.println("Max Value: " + Collections.max(numbers)); // 89

        // 4. shuffle() - Randomizes order using Fisher-Yates:
        Collections.shuffle(numbers);
        System.out.println("Shuffled: " + numbers);

        // 5. unmodifiableList() - Creates read-only wrapper:
        List<Integer> readOnly = Collections.unmodifiableList(numbers);
        // readOnly.add(99); // Throws UnsupportedOperationException!
    }
}

Next Step

Congratulations on mastering the Java Collections Framework! Let us now step into Section 6: Generics, Lambdas, Functional Programming & Concurrency. Proceed to: Java Generics & Wildcards →

Frequently Asked Questions (FAQ)

Q1. What is the difference between Collection and Collections in Java?
Collection is the root interface in the Java Collections Framework. Collections is an abstract utility class containing purely static methods (like Collections.sort(), Collections.shuffle()) for operating on collections.
Q2. What is Collections.unmodifiableList() in Java?
It returns an unmodifiable read-only wrapper view of the specified list. Any attempt to modify the returned list (via add(), remove(), or set()) throws an UnsupportedOperationException.
Q3. How do you make a standard ArrayList thread-safe using Collections?
Wrap the list with Collections.synchronizedList(new ArrayList<>()): every method call is wrapped with an internal object mutex lock.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Collections Hierarchy →

Root framework overview.

Java ArrayList →

List manipulation.

Comparable vs Comparator →

Custom sorting arguments.

Java Generics →

Entering Section 6: Generics & Streams.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!