← Back to Chapters

Collections Utility Class

? Collections Utility Class

? Quick Overview

The Collections utility class in Java is part of the java.util package. It provides static methods to operate on collection objects such as sorting, searching, reversing, synchronizing, and making collections unmodifiable.

? Key Concepts

  • Contains only static methods
  • Works with List, Set, and Map
  • Helps reduce manual algorithm code
  • Improves readability and reliability

? Syntax / Theory

The Collections class cannot be instantiated. All methods are accessed using the class name.

? View Code Example
// Importing Collections utility class
import java.util.Collections;
import java.util.List;

? Code Example(s)

? View Code Example
// Demonstrating common Collections utility methods
import java.util.*;

public class CollectionsDemo {
public static void main(String[] args) {

List numbers = new ArrayList<>();

numbers.add(40);
numbers.add(10);
numbers.add(30);
numbers.add(20);

Collections.sort(numbers);
System.out.println(numbers);

Collections.reverse(numbers);
System.out.println(numbers);

int index = Collections.binarySearch(numbers, 20);
System.out.println(index);
}
}

? Live Output / Explanation

Output Explanation

  • sort() arranges elements in ascending order
  • reverse() reverses the current order
  • binarySearch() finds the index of an element

? Interactive Collections Playground

Click the buttons to visualize how Java methods affect a List.

 
> Ready. Waiting for command...

? Tips & Best Practices

  • Always use generics to avoid ClassCastException
  • Use Collections.unmodifiableList() for read-only data
  • Prefer utility methods over custom algorithms

? Try It Yourself

  • Create a list of strings and sort alphabetically
  • Find maximum and minimum elements using Collections
  • Convert a list into a synchronized list