Collections class in java is a useful utility class to work with collections in java. The java.util.Collections class directly extends the Object class and exclusively consists of the static methods that operate on Collections or return them.

Collections Class in java

Collections class contains polymorphic algorithms that operate on collections and “wrappers” — which return a new collection backed by a specified collection. It is a member of Java Collections Framework.

The documentation for the polymorphic algorithms included in this class generally includes a brief description of the implementation which is regarded as the implementation notes, rather than parts of the specification.

While implementing these methods, we can substitute with other algorithms, so long as the specification itself is adhered to. For example, the algorithm used by Collections.sort() does not have to be a mergesort, but it does have to be stable.

Collections class fields

Collections class contains 3 fields: EMPTY_LIST, EMPTY_SET, EMPTY_MAP, which can be used to get immutable empty List, Map and Set respectively.

Collection class methods

Let’s take an example collection and walk through different methods provided by Collections class in java.

  1. boolean addAll(Collection c, T... elements): This method adds all of the provided elements to the specified collection at once. The elements can be provided as a comma-separated list.

    The output for this will be:
  2. void sort(List list, Comparator c): This method sorts the provided list according to the natural ordering. We can also pass in s Comparator, if we want some custom ordering.

  3. Queue asLifoQueue(Deque deque): This method returns a view of Deque as a Last-in-first-out (Lifo) Queue.
    The methods add and remove are mapped to push, pop respectively and so on. This can be useful when we would like to use a method requiring a Queue but we need Lifo ordering.

  4. int binarySearch(List<? extends Comparable> list, T key): This method searches the key using binary search in the specified list. The list should be sorted by natural ordering, before calling this method, otherwise, the result will be undefined.It returns the index of the element in the sorted list if the element is found, in other cases, it returns (-(insertion point)-1). Where, the insertion point is defined as the point at which the key would be inserted into the list, i.e. the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key.
    Note that this guarantees that the return value will be >= 0 if the key is found.

    The output:

    We can also pass in a Comparator, which indicates that the list is sorted in the order induced by the specified comparator
  5. Collection checkedCollection(Collection c, Class type): This method provides a dynamically typesafe view of the provided collection. It is useful to keep an eye on the collection, that any wrongly typed element is not inserted in it.

  6. Collections-Class-in-javaSimilarly, we have check methods for specific collections such as List, Map, Set, etc.
  7. void copy(List dest, List src): This method copies all of the elements from source list to destination list. After this operation is performed, the index of each copied element in the destination list will be identical to its index in the source list.In the previous method example, we created a list which contains 5 elements. Let’s copy out “fruits” list to this list and see what happens:

    The output will be:

    The destination list must be at least as long as the source list. In our example, it is longer than the source list, so in this case, the remaining elements in the destination list are unaffected (here, “four” and “10”).
  8. boolean disjoint(Collection c1, Collection c2): This method returns true if the two specified collections have no elements in common.In the previous example we copied the fruits to list, so now they are not disjoint. So, when we execute:

    The output will be:

    Let’s create another list for “vegetables” and check if it is disjoint to “fruits”.

    The output is:

    If we pass a same collection in both arguments, we get false, unless they are empty:

  9. void fill(List list, T obj): This method replaces all of the elements of the specified list with the specified element.
    If we fill our “list” list, all its five elements will be replaced:

  10. int frequency(Collection c, Object o): This method returns the number of elements in the specified collection which are equal to the specified object.From our previous example, if we say:

    It returns :
  11. int indexOfSubList(List source, List target): This 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.For example, if we create a sublist for our “fruit” list:

    We get the ourput:

    Because this sublist starts from index 1 of fruits.
    Now, if we try to do the same for another sublist that does not exist:

    We get:

    Also note that if the size of sublist > size of the list, we get -1.
    We have another method int lastIndexOfSubList(List source, List target), that just returns the last index for the specified sublist, otherwise, produces same output as this one.
  12. static ArrayList list(Enumeration e) and Enumeration enumeration(Collection c): These methods returns an array list from enumeration and an enumeration from a collection, respectively, so as to provide interoperability between legacy APIs that return enumerations and new APIs that require collections.
  13. T max(Collection coll, Comparator comp): This method returns the maximum element in collection according to the natural ordering of elements.


    We can also pass the Comparator inside this method if we want a custom ordering.
    Similarly min method is also available, which can also be used with or without the Comparator.
  14. Collection<T> synchronizedCollection(Collection<T> c): This method returns a synchronized (thread-safe) collection backed by the provided collection. It’s convinient to get synchronized collections from any collection object as and when required. API also provides us with synchronizedList method which returns thread-safe list backed by provided list in the argument.

    Also, There are synchronizedMap, synchronizedSet, synchronizedSortedSet as well as synchronizedSortedMap methods available which do the similar job.

These are the frequently used methods, apart from which we also have other methods like newSetFromMap, replaceAll, swap, reverse, etc.

Note that all the methods of this class throw a NullPointerException if the collections or class objects provided to them are null.

The “destructive” algorithms — algorithms that modify the collection on which they operate, contained in this class, are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitives.

Also, these algorithms may, or may not throw this exception if an invocation would have no effect on the collection. For example, invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException.

That’s all for the Collections class.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: