Java Collections Util Class Methods Tutorial with Examples

The Collections class in Java provides static methods that operate on or return collections. It contains methods for collection operations such as sorting, searching, reversing, shuffling, and more. This tutorial will cover all methods of the Collections utility class with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.

Table of Contents

  1. Introduction
  2. Key Points
  3. Collections Methods
    • sort()
    • reverse()
    • shuffle()
    • binarySearch()
    • copy()
    • fill()
    • max()
    • min()
    • nCopies()
    • replaceAll()
    • rotate()
    • swap()
    • unmodifiableCollection()
    • synchronizedCollection()
    • frequency()
    • disjoint()
    • indexOfSubList()
    • lastIndexOfSubList()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example with CRUD Operations
  8. Conclusion

1. Introduction

The Collections class in Java is a part of the java.util package and provides static methods that operate on or return collections. It includes various algorithms and helper methods for common collection operations.

2. Key Points

  • Collections class contains static methods only.
  • It provides utility methods for collection operations.
  • Methods can perform operations such as sorting, searching, and modifying collections.
  • It includes thread-safe methods for creating synchronized collections.

3. Collections Methods

3.1. sort()

The sort() method sorts the specified list into ascending order, according to the natural ordering of its elements.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        Collections.sort(fruits);
        System.out.println(fruits);
    }
}

Output:

[Apple, Banana, Mango]

3.2. reverse()

The reverse() method reverses the order of the elements in the specified list.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        Collections.reverse(fruits);
        System.out.println(fruits);
    }
}

Output:

[Banana, Mango, Apple]

3.3. shuffle()

The shuffle() method randomly shuffles the elements in the specified list.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        Collections.shuffle(fruits);
        System.out.println(fruits);
    }
}

Output:

[Mango, Apple, Banana]

3.4. binarySearch()

The binarySearch() method searches the specified list for the specified key using the binary search algorithm. The list must be sorted into ascending order.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        Collections.sort(fruits);
        int index = Collections.binarySearch(fruits, "Mango");
        System.out.println("Index of Mango: " + index);
    }
}

Output:

Index of Mango: 2

3.5. copy()

The copy() method copies all of the elements from one list into another.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("Apple");
        source.add("Mango");
        source.add("Banana");

        List<String> destination = new ArrayList<>(source.size());
        destination.addAll(source); // Ensuring the destination list is of the same size
        Collections.copy(destination, source);
        System.out.println(destination);
    }
}

Output:

[Apple, Mango, Banana]

3.6. fill()

The fill() method replaces all of the elements of the specified list with the specified element.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        Collections.fill(fruits, "Orange");
        System.out.println(fruits);
    }
}

Output:

[Orange, Orange, Orange]

3.7. max()

The max() method returns the maximum element of the given collection, according to the natural ordering of its elements.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        String maxFruit = Collections.max(fruits);
        System.out.println("Max fruit: " + maxFruit);
    }
}

Output:

Max fruit: Mango

3.8. min()

The min() method returns the minimum element of the given collection, according to the natural ordering of its elements.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        String minFruit = Collections.min(fruits);
        System.out.println("Min fruit: " + minFruit);
    }
}

Output:

Min fruit: Apple

3.9. nCopies()

The nCopies() method returns an immutable list consisting of n copies of the specified object.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> copies = Collections.nCopies(3, "Orange");
        System.out.println(copies);
    }
}

Output:

[Orange, Orange, Orange]

3.10. replaceAll()

The replaceAll() method replaces all occurrences of one specified value in the list with another.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Apple");
        Collections.replaceAll(fruits, "Apple", "Orange");
        System.out.println(fruits);
    }
}

Output:

[Orange, Mango, Orange]

3.11. rotate()

The rotate() method rotates the elements in the specified list by the specified distance.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        Collections.rotate(fruits, 1);
        System.out.println(fruits);
    }
}

Output:

[Banana, Apple, Mango]

3.12. swap()

The swap() method swaps the elements at the specified positions in the specified list.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        Collections.swap(fruits, 0, 2);
        System.out.println(fruits);
    }
}

Output:

[Banana, Mango, Apple]

3.13. unmodifiableCollection()

The unmodifiableCollection() method returns an unmodifiable view of the specified collection.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        List<String> unmodifiableFruits = Collections.unmodifiableList(fruits);
        System.out.println



(unmodifiableFruits);
    }
}

Output:

[Apple, Mango, Banana]

3.14. synchronizedCollection()

The synchronizedCollection() method returns a synchronized (thread-safe) collection backed by the specified collection.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        List<String> synchronizedFruits = Collections.synchronizedList(fruits);
        System.out.println(synchronizedFruits);
    }
}

Output:

[Apple, Mango, Banana]

3.15. frequency()

The frequency() method returns the number of occurrences of the specified element in the specified collection.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Apple");
        int frequency = Collections.frequency(fruits, "Apple");
        System.out.println("Frequency of Apple: " + frequency);
    }
}

Output:

Frequency of Apple: 2

3.16. disjoint()

The disjoint() method returns true if the two specified collections have no elements in common.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits1 = new ArrayList<>();
        fruits1.add("Apple");
        fruits1.add("Mango");

        List<String> fruits2 = new ArrayList<>();
        fruits2.add("Banana");
        fruits2.add("Orange");

        boolean isDisjoint = Collections.disjoint(fruits1, fruits2);
        System.out.println("Are the two lists disjoint? " + isDisjoint);
    }
}

Output:

Are the two lists disjoint? true

3.17. indexOfSubList()

The indexOfSubList() method returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Orange");

        List<String> target = new ArrayList<>();
        target.add("Mango");
        target.add("Banana");

        int index = Collections.indexOfSubList(fruits, target);
        System.out.println("Index of sublist: " + index);
    }
}

Output:

Index of sublist: 1

3.18. lastIndexOfSubList()

The lastIndexOfSubList() method returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.

Example:

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

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Orange");

        List<String> target = new ArrayList<>();
        target.add("Mango");
        target.add("Banana");

        int lastIndex = Collections.lastIndexOfSubList(fruits, target);
        System.out.println("Last index of sublist: " + lastIndex);
    }
}

Output:

Last index of sublist: 1

4. Use Cases

  • Sorting and Searching: Sorting lists and performing binary search operations.
  • Data Manipulation: Reversing, shuffling, rotating, and swapping elements in collections.
  • Synchronization: Creating synchronized collections for thread-safe operations.
  • Immutability: Creating unmodifiable collections to prevent modifications.

5. Best Practices

  • Use immutability where possible: Use unmodifiable collections to create read-only views.
  • Ensure thread safety: Use synchronized collections when multiple threads access the collection.
  • Understand collection operations: Be familiar with various utility methods for effective data manipulation.

6. Performance Considerations

  • Algorithmic complexity: Understand the algorithmic complexity of operations like sort, binary search, and shuffle.
  • Thread safety overhead: Be aware of the overhead associated with creating synchronized collections.

7. Real-time Example with CRUD Operations

Managing a Student Database:

Student.java:

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + "}";
    }
}

Main.java:

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

public class Main {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();

        // Create
        studentList.add(new Student("Aarav", 20));
        studentList.add(new Student("Vivaan", 22));
        studentList.add(new Student("Diya", 21));

        // Read
        System.out.println("Students:");
        studentList.forEach(System.out::println);

        // Update
        studentList.set(1, new Student("Vivaan", 23));
        System.out.println("After Update:");
        studentList.forEach(System.out::println);

        // Delete
        studentList.remove(0);
        System.out.println("After Deletion:");
        studentList.forEach(System.out::println);

        // Sort
        studentList.sort((s1, s2) -> s1.getName().compareTo(s2.getName()));
        System.out.println("After Sorting:");
        studentList.forEach(System.out::println);

        // Reverse
        Collections.reverse(studentList);
        System.out.println("After Reversing:");
        studentList.forEach(System.out::println);

        // Shuffle
        Collections.shuffle(studentList);
        System.out.println("After Shuffling:");
        studentList.forEach(System.out::println);
    }
}

Output:

Students:
Student{name='Aarav', age=20}
Student{name='Vivaan', age=22}
Student{name='Diya', age=21}
After Update:
Student{name='Aarav', age=20}
Student{name='Vivaan', age=23}
Student{name='Diya', age=21}
After Deletion:
Student{name='Vivaan', age=23}
Student{name='Diya', age=21}
After Sorting:
Student{name='Diya', age=21}
Student{name='Vivaan', age=23}
After Reversing:
Student{name='Vivaan', age=23}
Student{name='Diya', age=21}
After Shuffling:
Student{name='Diya', age=21}
Student{name='Vivaan', age=23}

8. Conclusion

The Collections utility class in Java provides a comprehensive set of static methods for performing common collection operations. By understanding its methods, use cases, and best practices, you can effectively utilize the Collections class in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.

Comments