java.util.Collections Class API Guide

In this guide, we will take a look into the usage of java.util.Collections class methods/API's with examples.
java.util.Collections class consists exclusively of static methods that operate on or return collections.
It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.

Important java.util.Collections methods

  • sort(List list)
  • sort(List list, Comparator<? super Project> c)
  • shuffle(List<?> list)
  • reverse(List<?> list)
  • rotate(List<?> list, int distance)
  • swap(List<?> list, int i, int j)
  • replaceAll(List list, String oldVal, String newVal)
  • copy(List<? super String> dest, List<? extends String> src)
  • Collections.binarySearch(list, "element 4")
  • frequency(Collection<?> c, Object o)
  • disjoint(Collection> c1, Collection> c2)
  • min(Collection extends ?> coll)
  • max(Collection extends ?> coll)

java.util.Collections Class

The Collections class provides static methods whose first argument is the collection on which the operation is to be performed.
We use the Collections utility class to demonstrate the below Algorithms with examples:
  • Sorting
  • Shuffling
  • Routine Data Manipulation
  • Searching
  • Composition
  • Finding Extreme Values

Sorting using java.util.Collections Class

The Collections class provides two overloaded sorting methods:

sort(List list)

This method sorts the specified list into ascending order, according to the natural ordering of its elements. 
All elements in the list must implement a Comparable interface.
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");
// Sorts the specified list into ascending order, according to
// the natural ordering of its elements.
Collections.sort(list);
for (String str : list) {
    System.out.println(" sort elements in ascending order  --" + str);
}
Output:
 sort elements in ascending order  --element 1
 sort elements in ascending order  --element 2
 sort elements in ascending order  --element 3
 sort elements in ascending order  --element 4

sort(List list, Comparator<? super Project> c)

This method sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list). 
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CollectionsClassExamples {

    public static void main(String[] args) {
        sortingCustomObjectsByComparator();
    }

    private static void sortingCustomObjectsByComparator() {
        // Sort Projects by project id in ascending order.
        List<Project> projects = new ArrayList<>();
        Project project = new Project();
        project.setProjectId(100);
        project.setProjectName("TMS");
        projects.add(project);

        Project project2 = new Project();
        project2.setProjectId(200);
        project2.setProjectName("APEX");
        projects.add(project2);

        Project project3 = new Project();
        project3.setProjectId(50);
        project3.setProjectName("CMS");
        projects.add(project3);

        // Sorting project by project name in ascending order in Java
        Collections.sort(projects, Comparator.comparing(Project::getProjectName));
        printList(projects);

    }

    private static void printList(List<Project> projects) {
        for (Project project : projects) {
            System.out.println(project.getProjectId());
            System.out.println(project.getProjectName());
        }
    }

}

class Project implements Comparable<Project> {
    private int projectId;
    private String projectName;

    public int getProjectId() {
        return projectId;
    }

    public void setProjectId(int projectId) {
        this.projectId = projectId;
    }

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    @Override
    public int compareTo(Project project) {
        return this.getProjectId() - project.getProjectId();
    }
}
Output:
200
APEX
50
CMS
100
TMS

Shuffling using java.util.Collections Class

The shuffle algorithm does the opposite of what sort does, destroying any trace of order that may have been present in a List. That is, this algorithm reorders the List based on input from a source of randomness such that all possible permutations occur with equal likelihood, assuming a fair source of randomness. 
Let's understand the Collections utility class provided the shuffling methods with an example.

shuffle(List<?> list)

This method randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.
Example:
    private static void shuffleAlgorithmsDemo() {
        List<String> list = new LinkedList<>();
        list.add("element 2");
        list.add("element 1");
        list.add("element 4");
        list.add("element 3");

        Collections.sort(list);
        for (String str : list) {
            System.out.println(" sort elements in ascending order  --" + str);
        }

        // randomly permutes the elements in a List.
        Collections.shuffle(list);
        for (String str : list) {
            System.out.println(" sort elements in ascending order  --" + str);
        }
    }
Output:
 sort elements in ascending order  --element 2
 sort elements in ascending order  --element 3
 sort elements in ascending order  --element 4
 shuffle elements  --element 1
 shuffle elements  --element 3
 shuffle elements  --element 4
 shuffle elements  --element 2

Routine Data Manipulation

The Collections class provides five algorithms for doing routine data manipulation on List objects, all of which are pretty straightforward:
  • reverse - reverses the order of the elements in a List.
  • fill - overwrites every element in a list with the specified value. This operation is useful for reinitializing a List.
  • copy - takes two arguments, a destination List, and a source list, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected.
  • swap - swaps the elements at the specified positions in a List.
  • addAll - Adds all the specified elements to a Collection. The elements to be added may be specified individually or as an array.

reverse(List<?> list)

This method reverses the order of the elements in the specified list.
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

Collections.sort(list);
for(String str : list){
     System.out.println(" sort elements in ascending order  --" + str);
}
//reverses the order of the elements in a List.
Collections.reverse(list);

rotate(List<?> list, int distance)

This method rotates the elements in the specified list by the specified distance. 
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

// rotates all the elements in a List by a specified distance.
Collections.rotate(list, 1);

swap(List<?> list, int i, int j)

This method swaps the elements at the specified positions in the specified list. 
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

//swaps the elements at specified positions in a List.
Collections.swap(list, 0, 1);
printMessage(list, "swap elements ");

replaceAll(List list, String oldVal, String newVal)

This method replaces all occurrences of one specified value in a list with another. 
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

//replaces all occurrences of one specified value with another.
Collections.replaceAll(list, "element 3", "element 6");

copy(List<? super String> dest, List<? extends String> src)

This method copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");

List<String> destList = new ArrayList<>();
Collections.copy(destList, list);

Searching using Collections Class

The binarySearch algorithm searches for a specified element in a sorted list. This algorithm has two forms. 
The first takes a List and an element to search for (the "search key"). This form assumes that the list is sorted in ascending order according to the natural ordering of its elements.
The second form takes a Comparator in addition to the List and the search key and assumes that the list is sorted into ascending order according to the specified Comparator
The sort algorithm can be used to sort the List prior to calling binarySearch
Example:
private static void searchingAlgorithmsDemo() {
    List<String> list = new LinkedList<>();
    list.add("element 2");
    list.add("element 1");
    list.add("element 4");
    list.add("element 3");
 
    Collections.sort(list);
    for (String str : list) {
        System.out.println(" sort elements in ascending order  --" + str);
    }
    int index = Collections.binarySearch(list, "element 4");
    System.out.println("Element found at ::" + index);
}
Output:
 sort elements in ascending order  --element 1
 sort elements in ascending order  --element 2
 sort elements in ascending order  --element 3
 sort elements in ascending order  --element 4
 Element found at ::3

Composition

The frequency and disjoint algorithms test some aspects of the composition of one or more Collections:
  • frequency - counts the number of times the specified element occurs in the specified collection.
  • disjoint - determines whether two Collections are disjoint; that is, whether they contain no elements in common.

frequency(Collection<?> c, Object o)

This method returns the number of elements in the specified collection equal to the specified object. 
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 1");
list.add("element 3");
//Returns the number of elements in the specified collection         
//equal to the specified object.
System.out.println(Collections.frequency(list, "element 1"));

disjoint(Collection> c1, Collection> c2)

This method returns true if the two specified collections have no elements in common.
Example:
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 1");
list.add("element 3");
//Returns the number of elements in the specified collection         
//equal to the specified object.

System.out.println(Collections.frequency(list, "element 1"));
List<String> list2 = new LinkedList<>();
list2.add("element 2");
list2.add("element 1");
list2.add("element 1");
list2.add("element 3");
//Returns true if the two specified collections have no elements in common. 
System.out.println(Collections.disjoint(list, list2));

Finding Extreme Values(min and max methods)

The min and the max algorithms return, respectively, the minimum and maximum elements contained in a specified Collection. Both of these operations come in two forms. 
The simple form takes only a Collection and returns the minimum (or maximum) element according to the elements' natural ordering. 
The second form takes a Comparator in addition to the Collection and returns the minimum (or maximum) element according to the specified Comparator.

min(Collection extends ?> coll)

This method returns the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement a Comparable interface. 
Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the collection). Example:
List<Integer> list = new LinkedList<>();
list.add(100);
list.add(300);
list.add(200);
list.add(500);
// Returns the minimum element of the given collection, 
// according to the natural ordering of its elements.
// All elements in the collection must implement the Comparable interface.
System.out.println(Collections.min(list));

max(Collection extends ?> coll)

This method returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement a Comparable interface. 
Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).
Example:
List<Integer> list = new LinkedList<>();
list.add(100);
list.add(300);
list.add(200);
list.add(500);
//All elements in the collection must implement the Comparable interface. 
System.out.println(Collections.max(list));

References

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/Collections.html

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course