Collections Class In Java

Collections Class In Java | The Collections class defines several utility methods for collection objects like sorting, searching, reversing, etc.

Sorting Elements in the List

Collection class defines the following 2 sort() methods:-

  • public static void sort(List list):- To sort based on default natural sorting order. In this case, the list should compulsorily contain homogenous and comparable objects otherwise we will get RuntimeException:- ClassCastException. To sort the list of elements, the comparison is required therefore the list should not contain null, or else we get NullPointerException.
  • public static void sort(List l, Comparator c):- To sort based on customized sorting order.

Program to sort elements list according to the default natural sorting order.

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

public class Test {
    public static void main(String[] args) {
        List<String> al = new ArrayList<String>();
        al.add("Z");
        al.add("A");
        al.add("K");
        al.add("N");
        // al.add(null);
        System.out.println("Before Sorting: " + al); // [Z, A, K, N]
        
        Collections.sort(al);
        System.out.println("After Sorting: " + al); // [A, K, N, Z]

    }
}

Program to sort elements of a list according to Customized sorting order

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

public class Test {
    public static void main(String[] args) {
        List<String> al = new ArrayList<String>();
        al.add("Z");
        al.add("A");
        al.add("K");
        al.add("N");
        System.out.println("Before Sorting: " + al); // [Z, A, K, N]

        Collections.sort(al, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s2.compareTo(s1);
            }
        });
        System.out.println("After Sorting: " + al); // [Z, N, K, A]
    }
}

Searching Elements in List

The Collections class defines the following binary search method:-

  1. public static int binarySearch(List ls, Object target):- If the list is sorted according to the default natural sorting order then we have to use this method.
  2. public static int binarySearch(List ls, Object target, Comparator c):- We have to use this method If the list is sorted according to customized sorting order.
  • The above search method internally uses a binary search algorithm.
  • Successful search returns:- index.
  • Unsuccessful search returns:- Insertion point.
  • The insertion point is the location where we can place the target element in the sorted list.
  • Before calling the binarySearch() method list must be sorted otherwise we will get unpredictable results.
  • If the list is sorted according to the comparator then at the time of the search operation also we have to pass the same comparator object otherwise we will get unpredictable results.
-1-2-3-4-5-6 (These are Insertion Point)
AKMZa
01234(Index Point)

Program to search elements in the List while using default natural sorting order.

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

public class Test {
    public static void main(String[] args) {
        List<String> al = new ArrayList<String>();
        al.add("A");
        al.add("K");
        al.add("M");
        al.add("Z");
        al.add("a");
        System.out.println(al); // [A, K, M, Z, a]

        Collections.sort(al);
        System.out.println(Collections.binarySearch(al, "Z")); // 3
        System.out.println(Collections.binarySearch(al, "J")); // -2
    }
}

Program to search elements while using customized sorting order.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> al = new ArrayList<Integer>();
        al.add(15);
        al.add(0);
        al.add(20);
        al.add(10);
        al.add(5);
        System.out.println(al); // [15, 0, 20, 10, 5]

        Comparator<Integer> reverseOrder = new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        };

        Collections.sort(al, reverseOrder);
        System.out.println(al); // [20, 15, 10, 5, 0]

        System.out.println(Collections.binarySearch(al, 10, reverseOrder)); // 2
        System.out.println(Collections.binarySearch(al, 13, reverseOrder)); // -3
        System.out.println(Collections.binarySearch(al, 17)); // unpredicatable result

    }
}

After sorting:-

-1-2-3-4-5-6 (These are insertion order)
20151050
01234Index

Here list is sorted based on customized sorting but when we call Collections.binarySearch(al, 17) without passing the comparator object then we will get unpredictable results.

For the list of N elements in the case of binarySearch method:-

  • Successful search result range: 0 to n-1
  • Unsuccessful search result range: -(n+1) to -1
  • Total result range: -(n+1) to n-1

Example:- 3 Elements,

-1-2-3-4 (These are insertion order)
AKZ
012Index
  • Successful search result range: 0 to 2
  • Unsuccessful search result range: -4 to -1
  • Total result range: -4 to 2

Reversing Elements in List

The Collection class defines the following reverse() method to reverse elements in the list:- public static void reverse(List list)

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

public class Test {
    public static void main(String[] args) {
        List<Integer> al = Arrays.asList(15, 0, 20, 10, 5);
        System.out.println(al); // [15, 0, 20, 10, 5]

        // reverse the order of the elements
        Collections.reverse(al);
        System.out.println(al); // [5, 10, 20, 0, 15]

    }
}

reverse() vs reverseOrder()

We can use the reverse() method to reverse the order of elements of the list whereas we can use the reverseOrder() method to get the reversed Comparator.

Comparator c1 = Collection reverseOrder(Comparator c);
Here “c1” is for descending order whereas “c” is for ascending order.

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Integer> al = List.of(15, 0, 20, 10, 5);
        System.out.println(al); // [15, 0, 20, 10, 5]

        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1); // descending order
            }
        };

        // ascending order
        Comparator<Integer> reverseComparator = Collections.reverseOrder(comparator);

        List<Integer> defaultSorted = al.stream().sorted(comparator).collect(Collectors.toList());
        System.out.println(defaultSorted); // [20, 15, 10, 5, 0]
        
        List<Integer> reverseSorted = al.stream().sorted(reverseComparator).collect(Collectors.toList());
        System.out.println(reverseSorted); // [0, 5, 10, 15, 20]

    }
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *