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
Collection class methods
Let’s take an example collection and walk through different methods provided by Collections class in java.
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.CopyList fruits = new ArrayList(); Collections.addAll(fruits, "Apples", "Oranges", "Banana"); fruits.forEach(System.out::println);
The output for this will be:CopyApples Oranges Banana
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.CopyCollections.sort(fruits); System.out.println("Sorted according to natural ordering:"); fruits.forEach(System.out::println); Collections.sort(fruits, Comparator.reverseOrder()); System.out.println("Sorted according to reverse of natural ordering:"); fruits.forEach(System.out::println);
Output:CopySorted according to natural ordering: Apples Banana Oranges Sorted according to reverse of natural ordering: Oranges Banana Apples
Queue asLifoQueue(Deque deque): This method returns a view of
Dequeas a Last-in-first-out (Lifo)
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.CopyDeque deque = new LinkedList(); deque.addFirst("Apples"); deque.add("Oranges"); deque.addLast("Bananas"); Queue queue = Collections.asLifoQueue(deque); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll());
Output:CopyApples Oranges Banana
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.CopyCollections.sort(fruits); System.out.println(Collections.binarySearch(fruits, "Banana")); System.out.println(Collections.binarySearch(fruits, "Grapes"));
The output:Copy1 -3
We can also pass in a
Comparator, which indicates that the list is sorted in the order induced by the specified comparator
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.CopyList list = new ArrayList(); Collections.addAll(list, "one", "two", "three", "four"); Collection checkedList = Collections.checkedCollection(list, String.class); System.out.println("Checked list content: " + checkedList); //we can add any type of element to list list.add(10); //we cannot add any type of elements to chkList, doing so //throws ClassCastException checkedList.add(10);
Similarly, we have check methods for specific collections such as
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:CopyCollections.copy(list, fruits); list.forEach(System.out::println);
The output will be:CopyOranges Banana Apples four 10
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”).
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:CopySystem.out.println(Collections.disjoint(list, fruits));
The output will be:Copyfalse
Let’s create another list for “vegetables” and check if it is disjoint to “fruits”.CopyList vegetables = new ArrayList(); Collections.addAll(vegetables, "Potato", "Cabbage"); System.out.println(Collections.disjoint(vegetables, fruits));
The output is:Copytrue
If we pass a same collection in both arguments, we get false, unless they are empty:CopySystem.out.println(Collections.disjoint(vegetables, vegetables)); System.out.println(Collections.disjoint(new ArrayList(), new ArrayList()));
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:CopyCollections.fill(list, "filled with dummy data"); list.forEach(System.out::println);
Output:Copyfilled with dummy data filled with dummy data filled with dummy data filled with dummy data filled with dummy data
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:CopySystem.out.println(Collections.frequency(list, "filled with dummy data"));
It returns :Copy5
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:CopyList fruitsSubList1 = new ArrayList(); Collections.addAll(fruitsSubList1, "Oranges", "Banana"); System.out.println(Collections.indexOfSubList(fruits, fruitsSubList1));
We get the ourput:Copy1
Because this sublist starts from index 1 of fruits.
Now, if we try to do the same for another sublist that does not exist:CopyList fruitsSubList2 = new ArrayList(); Collections.addAll(fruitsSubList2, "Kiwi", "Pinapple"); System.out.println(Collections.indexOfSubList(fruits, fruitsSubList2));
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.
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.
T max(Collection coll, Comparator comp): This method returns the maximum element in collection according to the natural ordering of elements.CopySystem.out.println(Collections.max(fruits));
We can also pass the
Comparatorinside this method if we want a custom ordering.
minmethod is also available, which can also be used with or without the
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
synchronizedListmethod which returns thread-safe list backed by provided list in the argument.CopyCollection<String> synchronizedCollection = Collections.synchronizedCollection(fruits); List<String> synchronizedList = Collections.synchronizedList(fruits);
Also, There are
synchronizedSortedSetas well as
synchronizedSortedMapmethods available which do the similar job.
These are the frequently used methods, apart from which we also have other methods like
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
That’s all for the
Reference: API Doc