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_MAP, which can be used to get immutable empty
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.
1234List fruits = new ArrayList();Collections.addAll(fruits, "Apples", "Oranges", "Banana");fruits.forEach(System.out::println);
The output for this will be:
1234<span style="color: #008000;"><strong><code>ApplesOrangesBanana</code></strong></span>
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.
12345678Collections.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);
12345678910<span style="color: #008000;"><strong><code>Sorted according to natural ordering:ApplesBananaOrangesSorted according to reverse of natural ordering:OrangesBananaApples</code></strong></span>
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.
123456789Deque 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());
1234<span style="color: #008000;"><strong><code>ApplesOrangesBanana</code></strong></span>
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.
1234Collections.sort(fruits);System.out.println(Collections.binarySearch(fruits, "Banana"));System.out.println(Collections.binarySearch(fruits, "Grapes"));
123<span style="color: #008000;"><strong><code>1-3</code></strong></span>
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.
12345678910List 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 listlist.add(10);//we cannot add any type of elements to chkList, doing so//throws ClassCastExceptioncheckedList.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:123Collections.copy(list, fruits);list.forEach(System.out::println);
The output will be:123456<span style="color: #008000;"><strong><code>OrangesBananaApplesfour10</code></strong></span>
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:1System.out.println(Collections.disjoint(list, fruits));
The output will be:1<span style="color: #008000;"><strong><code>false</code></strong></span>
Let’s create another list for “vegetables” and check if it is disjoint to “fruits”.1234List vegetables = new ArrayList();Collections.addAll(vegetables, "Potato", "Cabbage");System.out.println(Collections.disjoint(vegetables, fruits));
The output is:1<span style="color: #008000;"><strong><code>true</code></strong></span>
If we pass a same collection in both arguments, we get false, unless they are empty:123System.out.println(Collections.disjoint(vegetables, vegetables));System.out.println(Collections.disjoint(new ArrayList(), new ArrayList()));
Output:12<span style="color: #008000;"><strong><code>falsetrue</code></strong></span>
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:123Collections.fill(list, "filled with dummy data");list.forEach(System.out::println);
Output:12345<span style="color: #008000;"><strong><code>filled with dummy datafilled with dummy datafilled with dummy datafilled with dummy datafilled with dummy data</code></strong></span>
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:1System.out.println(Collections.frequency(list, "filled with dummy data"));
It returns :15
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:1234List fruitsSubList1 = new ArrayList();Collections.addAll(fruitsSubList1, "Oranges", "Banana");System.out.println(Collections.indexOfSubList(fruits, fruitsSubList1));
We get the ourput:1<span style="color: #008000;"><strong><code>1</code></strong></span>
Because this sublist starts from index 1 of fruits.
Now, if we try to do the same for another sublist that does not exist:123List 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.1System.out.println(Collections.max(fruits));
Output:1<span style="color: #008000;"><strong><code>Oranges</code></strong></span>
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.12345Collection<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