0% found this document useful (0 votes)
17 views21 pages

Collections Class in Java Is One of The Utility Classes in Java

Uploaded by

Sunil Mane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views21 pages

Collections Class in Java Is One of The Utility Classes in Java

Uploaded by

Sunil Mane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Java Course Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithrea

Collections Class in Java


Last Updated : 17 Dec, 2024

Collections class in Java is one of the utility classes in Java Collections


Framework. The java.util package contains the Collections class in Java.
Java Collections class is used with the static methods that operate on
the collections or return the collection. All the methods of this class
throw the NullPointerException if the collection or object passed to the
methods is null.

Example 1: Here, we will use ArrayList, which is a class from the Java
Collections framework. It allows to store elements in a list by
maintaining the insertion order and also allows duplicates.

Java

1 import java.util.ArrayList;
2
3 public class Geeks {
4 public static void main(String[] args) {
5
6 // Create an ArrayList to store elements
7 ArrayList<String> al = new ArrayList<>();
8
9 // Add elements to the list
10 al.add("Apple");
11 al.add("Banana");
12 al.add("Apple"); // Duplicates are allowed
13
14 System.out.println("" + al);
15 }

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 1/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

16 }

Output

[Apple, Banana, Apple]

Collection Class Declaration

public class Collections extends Object

Remember: Object is the parent class of all the classes.

Java Collection Class


Collection Framework contains both classes and interfaces. Although
both seem the same but there are certain differences between
Collection classes and the Collections framework.

To know the difference between Collection and Collections,


refer this article: Collection vs. Collections

The Collection classes in Java are mentioned below:

1. ArrayList

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 2/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

ArrayList is a class implemented using a list interface, in that provides


the functionality of a dynamic array where the size of the array is not
fixed.

Syntax:

ArrayList<_type_> var_name = new ArrayList<_type_>();

2. Vector

Vector is a Part of the collection class that implements a dynamic array


that can grow or shrink its size as required.

Syntax:

public class Vector<E> extends AbstractList<E> implements


List<E>, RandomAccess,
Cloneable, Serializable

3. Stack

Stack is a part of Java collection class that models and implements a


Stack data structure. It is based on the basic principle of last-in-first-
out(LIFO).

Syntax:

public class Stack<E> extends Vector<E>

4. LinkedList

LinkedList class is an implementation of the LinkedList data structure. It


can store the elements that are not stored in contiguous locations and
every element is a separate object with a different data part and
different address part.

Syntax:

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 3/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

LinkedList<_type_> var_name = new LinkedList<_type_>();

5. HashSet

HashSet is implemented using the Hashtable data structure. It offers


constant time performance for the performing operations like add,
remove, contains, and size.

Syntax:

public class HashSet<E> extends AbstractSet<E> implements


Set<E>, Cloneable, Serializable

6. LinkedHashSet

LinkedHashSet is an ordered version of HashSet that maintains a


doubly-linked List across all elements.

Syntax:

public class LinkedHashSet<E> extends HashSet<E> implements


Set<E>, Cloneable, Serializable

7. TreeSet

TreeSet class is implementations of the SortedSet interface in Java that


uses a Tree for storage. The ordering of the elements is maintained by a
set using their natural ordering whether an explicit comparator is
provided or not.

Syntax:

TreeSet<E> set = new TreeSet<>();

8. PriorityQueue

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 4/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

The PriorityQueue is based on the priority heap. The elements of the


priority queue are ordered according to the natural ordering, or by a
Comparator provided at queue construction time, depending on which
constructor is used.

Syntax:

public class PriorityQueue<E> extends AbstractQueue<E>


implements Serializable

9. ArrayDeque

The ArrayDeque class in Java is an implementation of the Deque


interface that uses a resizable array to store its elements. The
ArrayDeque class provides constant-time performance for inserting and
removing elements from both ends.

Syntax:

public class ArrayDeque<E> extends


AbstractCollection<E> implements Deque<E>,
Cloneable,Serializable

10. HashMap

HashMap Class is similar to HashTable but the data unsynchronized. It


stores the data in (Key, Value) pairs, and you can access them by an
index of another type.

Syntax:

public class HashMap<K,V> extends AbstractMap<K,V>


implements Map<K,V>, Cloneable, Serializable

11. EnumMap

EnumMap extends AbstractMap and implements the Map interface in


Java.
https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 5/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Syntax:

public class EnumMap<K extends Enum<K>,​V> extends


AbstractMap<K,​V> implements Serializable, Cloneable

12. AbstractMap

The AbstractMap class is a part of the Java Collection Framework. It


implements the Map interface to provide a structure to it, by doing so it
makes the further implementations easier.

Syntax:

public abstract class AbstractMap<K,V> implements Map<K,V>

13. TreeMap

A TreeMap is implemented using a Red-Black tree.TreeMap provides an


ordered collection of key-value pairs, where the keys are ordered based
on their natural order or a custom Comparator passed to the
constructor.

Syntax:

SortedMap<K, V> m = Collections.synchronizedSortedMap(new


TreeMap<>());

Java Collections Class Fields


The collection class contains 3 fields as listed below which can be used
to return immutable entities.

EMPTY_LIST to get an immutable empty List


EMPTY_SET to get an immutable empty Set
EMPTY_MAP to get an immutable empty Map

Now let us do discuss methods that are present inside this class so that
we can use these inbuilt functionalities later on in our program. Below

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 6/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

are the methods have been listed below in a tabular format as shown
below as follows:

Methods Description

It is used to insert the specified


addAll(Collection<? super T> c, T…
collection elements to the
elements)
specified collection.

This method returns a view of a


asLifoQueue​(Deque<T> deque) Deque as a Last-in-first-out (Lifo)
Queue.

This method searches the key


binarySearch(List<? extends
using binary search in the
Comparable> list, T key)
specified list.

This method searches the


binarySearch​(List<? extends T> list, specified list for the specified
T key, Comparator<? super T> c) object using the binary search
algorithm.

This method returns a dynamically


checkedCollection​(Collection<E> c,
typesafe view of the specified
Class<E> type)
collection.

checkedList​(List<E> list, Class<E> This method returns a dynamically


type) typesafe view of the specified list.

This method returns a dynamically


checkedMap​(Map<K,​V> m, Class<K>
typesafe view of the specified
keyType, Class<V> valueType)
map.

checkedNavigableMap​ This method returns a dynamically


(NavigableMap<K,​V> m, Class<K> typesafe view of the specified
keyType, Class<V> valueType) navigable map.

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 7/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Methods Description

This method returns a dynamically


checkedNavigableSet​
typesafe view of the specified
(NavigableSet<E> s, Class<E> type)
navigable set.

This method returns a dynamically


checkedQueue​(Queue<E> queue,
typesafe view of the specified
Class<E> type)
queue.

checkedSet​(Set<E> s, Class<E> This method returns a dynamically


type) typesafe view of the specified set.

checkedSortedMap​(SortedMap<K,​ This method returns a dynamically


V> m, Class<K> keyType, Class<V> typesafe view of the specified
valueType) sorted map.

This method returns a dynamically


checkedSortedSet​(SortedSet<E> s,
typesafe view of the specified
Class<E> type)
sorted set.

This method copies all of the


copy​(List<? super T> dest, List<?
elements from one list into
extends T> src)
another.

This method returns true if the


disjoint​(Collection<?> c1,
two specified collections have no
Collection<?> c2)
elements in common.

This method returns an


emptyEnumeration()
enumeration that has no elements.

This method returns an iterator


emptyIterator()
that has no elements.

This method returns an empty list


emptyList()
(immutable).

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 8/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Methods Description

This method returns a list iterator


emptyListIterator()
that has no elements.

This method returns an empty


emptyMap()
map (immutable).

This method returns an empty


emptyNavigableMap()
navigable map (immutable).

This method returns an empty


emptyNavigableSet()
navigable set (immutable).

This method returns an empty set


emptySet()
(immutable).

This method returns an empty


emptySortedMap()
sorted map (immutable).

This method returns an empty


emptySortedSet()
sorted set (immutable).

This method returns an


enumeration​(Collection<T> c) enumeration over the specified
collection.

This method replaces all of the


fill​(List<? super T> list, T obj) elements of the specified list with
the specified element.

This method returns the number of


elements in the specified
frequency​(Collection<?> c, Object o)
collection equal to the specified
object.

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 9/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Methods Description

This method returns the starting


position of the first occurrence of
indexOfSubList​(List<?> source,
the specified target list within the
List<?> target)
specified source list, or -1 if there
is no such occurrence.

This method returns the starting


position of the last occurrence of
lastIndexOfSubList​(List<?> source,
the specified target list within the
List<?> target)
specified source list, or -1 if there
is no such occurrence.

This method returns an array list


containing the elements returned
list​(Enumeration<T> e) by the specified enumeration in
the order they are returned by the
enumeration.

This method returns the maximum


element of the given collection,
max​(Collection<? extends T> coll)
according to the natural ordering
of its elements.

This method returns the maximum


max​(Collection<? extends T> coll, element of the given collection,
Comparator<? super T> comp) according to the order induced by
the specified comparator.

This method returns the minimum


element of the given collection,
min​(Collection<? extends T> coll)
according to the natural ordering
of its elements.

min​(Collection<? extends T> coll, This method returns the minimum


Comparator<? super T> comp) element of the given collection,

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 10/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Methods Description

according to the order induced by


the specified comparator.

This method returns an immutable


nCopies​(int n, T o) list consisting of n copies of the
specified object.

newSetFromMap​(Map<E,​Boolean> This method returns a set backed


map) by the specified map.

This method replaces all


replaceAll​(List<T> list, T oldVal, T
occurrences of one specified value
newVal)
in a list with another.

This method reverses the order of


reverse​(List<?> list)
the elements in the specified list

This method returns a comparator


that imposes the reverse of the
reverseOrder() natural ordering on a collection of
objects that implement the
Comparable interface.

This method returns a comparator


reverseOrder​(Comparator<T> cmp) that imposes the reverse ordering
of the specified comparator.

This method rotates the elements


rotate​(List<?> list, int distance) in the specified list by the specified
distance.

This method randomly permutes


shuffle​(List<?> list) the specified list using a default
source of randomness.

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 11/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Methods Description

This method randomly permute


shuffle​(List<?> list, Random rnd) the specified list using the
specified source of randomness.

This method returns an immutable


singletonMap​(K key, V value) map, mapping only the specified
key to the specified value.

This method returns an immutable


singleton​( T o) set containing only the specified
object.

This method returns an immutable


singletonList​( T o) list containing only the specified
object.

This method sorts the specified


list into ascending order, according
sort​(List<T> list)
to the natural ordering of its
elements.

This method sorts the specified


sort​(List<T> list, Comparator<?
list according to the order induced
super T> c)
by the specified comparator.

This method swaps the elements


swap​(List<?> list, int i, int j) at the specified positions in the
specified list.

This method returns a


synchronizedCollection​ synchronized (thread-safe)
(Collection<T> c) collection backed by the specified
collection.

synchronizedList​(List<T> list) This method returns a


synchronized (thread-safe) list

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 12/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Methods Description

backed by the specified list.

This method returns a


synchronizedMap​(Map<K,​V> m) synchronized (thread-safe) map
backed by the specified map.

This method returns a


synchronizedNavigableMap​ synchronized (thread-safe)
(NavigableMap<K,​V> m) navigable map backed by the
specified navigable map.

This method returns a


synchronizedNavigableSet​ synchronized (thread-safe)
(NavigableSet<T> s) navigable set backed by the
specified navigable set.

This method returns a


synchronizedSet​(Set<T> s) synchronized (thread-safe) set
backed by the specified set.

This method returns a


synchronizedSortedMap​ synchronized (thread-safe) sorted
(SortedMap<K,​V> m) map backed by the specified
sorted map.

This method returns a


synchronizedSortedSet​ synchronized (thread-safe) sorted
(SortedSet<T> s) set backed by the specified sorted
set.

This method returns an


unmodifiableCollection​(Collection<?
unmodifiable view of the specified
extends T> c)
collection.

unmodifiableList​(List<? extends T> This method returns an


list) unmodifiable view of the specified

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 13/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

Methods Description

list.

This method returns an


unmodifiableNavigableMap​
unmodifiable view of the specified
(NavigableMap<K,​? extends V> m)
navigable map.

This method returns an


unmodifiableNavigableSet​
unmodifiable view of the specified
(NavigableSet<T> s)
navigable set.

This method returns an


unmodifiableSet​(Set<? extends T>
unmodifiable view of the specified
s)
set.

This method returns an


unmodifiableSortedMap​
unmodifiable view of the specified
(SortedMap<K,​? extends V> m)
sorted map.

This method returns an


unmodifiableSortedSet​
unmodifiable view of the specified
(SortedSet<T> s)
sorted set.

Now, we have listed all the methods, It is clear how important they are
in writing optimized Java code. The Collections class is widely used and
its methods appear in almost every optimized Java program. Here, we
will implement these methods also discuss their operations.

Java Collections Example


Examples of Collections Classes in Java are mentioned below:

Adding Elements to the Collections


Sorting a Collection
Searching in a Collection
Copying Elements
Disjoint Collection

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 14/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

1. Adding Elements to the Collections Class Object

The addAll() method of java.util.Collections class is used to add all the


specified elements to the specified collection. Elements to be added
may be specified individually or as an array.

Example:

Java

1 // Adding Elements
2 // Using addAll() method
3
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.List;
7
8 class Geeks {
9
10 public static void main(String[] args) {
11
12 List<String> l = new ArrayList<>();
13
14 // Adding elements to the list
15 l.add("Shoes");
16 l.add("Toys");
17
18 // Add one or more elements
19 Collections.addAll(l, "Fruits", "Bat",
"Ball");
20
21 for (int i = 0; i < l.size(); i++) {
22 System.out.print(l.get(i) + " ");
23 }
24 }
25 }

Output

Shoes Toys Fruits Bat Ball

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 15/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

2. Sorting a Collection

Collections.sort() is used to sort the elements present in the specified


list of Collections in ascending order. Collections.reverseOrder() is used
to sort in descending order.

Example:

Java

1 // Sorting a Collections using sort() method


2 import java.util.ArrayList;
3 import java.util.Collections;
4 import java.util.List;
5
6 class Geeks {
7
8 public static void main(String[] args) {
9
10 List<String> l = new ArrayList<>();
11
12 // Adding elements to the list
13 // using add() method
14 l.add("Shoes");
15 l.add("Toys");
16
17 // Adding one or more
18 // element using addAll()
19 Collections.addAll(l, "Fruits", "Bat",
"Mouse");
20
21 // Sorting according to default ordering
22 // using sort() method
23 Collections.sort(l);
24
25 // Printing the elements
26 for (int i = 0; i < l.size(); i++) {
27 System.out.print(l.get(i) + " ");
28 }
29
30 System.out.println();
31
32 // Sorting according to reverse ordering
https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 16/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

33 Collections.sort(l,
Collections.reverseOrder());
34
35 // Printing the reverse order
36 for (int i = 0; i < l.size(); i++) {
37 System.out.print(l.get(i) + " ");
38 }
39 }
40 }

Output

Bat Fruits Mouse Shoes Toys


Toys Shoes Mouse Fruits Bat

3. Searching in a Collection

Collections.binarySearch() method returns the position of an object in a


sorted list. To use this method, the list should be sorted in ascending
order, otherwise, the result returned from the method will be wrong. If
the element exists in the list, the method will return the position of the
element in the sorted list, otherwise, the result returned by the method
would be the – (insertion point where the element should have been
present if exist)-1).

Example:

Java

1 // Binary Search using Collections.binarySearch()


2 import java.util.ArrayList;
3 import java.util.Collections;
4 import java.util.List;
5
6 public class Geeks {
7
8 public static void main(String[] args) {
9
10 List<String> l = new ArrayList<>();
11

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 17/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

12 // Adding elements to object


13 // using add() method
14 l.add("Shoes");
15 l.add("Toys");
16 l.add("Horse");
17 l.add("Ball");
18 l.add("Grapes");
19
20 // Sort the List
21 Collections.sort(l);
22
23 // BinarySearch on the List
24 System.out.println(
25 "The index of Horse is: "
26 + Collections.binarySearch(l, "Horse"));
27
28 // BinarySearch on the List
29 System.out.println(
30 "The index of Dog is: "
31 + Collections.binarySearch(l, "Dog"));
32 }
33 }

Output

The index of Horse is: 2


The index of Dog is: -2

4. Copying Elements

The copy() method of Collections class is used to copy all 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:

Java

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 18/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

1 // Copying Elements using copy() method


2 import java.util.ArrayList;
3 import java.util.Collections;
4 import java.util.List;
5
6 class Geeks {
7
8 public static void main(String[] args) {
9
10 List<String> l1 = new ArrayList<>();
11
12 // Add elements
13 l1.add("Shoes");
14 l1.add("Toys");
15 l1.add("Horse");
16 l1.add("Tiger");
17
18 // Print the elements
19 System.out.println(
20 "The Original Destination list is: ");
21
22 for (int i = 0; i < l1.size(); i++) {
23 System.out.print(l1.get(i) + " ");
24 }
25 System.out.println();
26
27 // Create source list
28 List<String> l2 = new ArrayList<>();
29
30 // Add elements
31 l2.add("Bat");
32 l2.add("Frog");
33 l2.add("Lion");
34
35 // Copy the elements from source to
destination
36 Collections.copy(l1, l2);
37
38 // Printing the modified list
39 System.out.println(
40 "The Destination List After copying is:
");
41
42 for (int i = 0; i < l1.size(); i++) {

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 19/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

43 System.out.print(l1.get(i) + " ");


44 }
45 }
46 }

Output

The Original Destination list is:


Shoes Toys Horse Tiger
The Destination List After copying is:
Bat Frog Lion Tiger

5. Disjoint Collection

Collections.disjoint() is used to check whether two specified collections


are disjoint or not. More formally, two collections are disjoint if they
have no elements in common. It returns true if the two collections do
not have any element in common.

Example:

Java

1 // Working of Disjoint Function


2 import java.util.ArrayList;
3 import java.util.Collections;
4 import java.util.List;
5
6 class Geeks {
7
8 public static void main(String[] args) {
9
10 List<String> l1 = new ArrayList<>();
11
12 // Add elements to l1
13 l1.add("Shoes");
14 l1.add("Toys");
15 l1.add("Horse");
16 l1.add("Tiger");
17

https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 20/26
12/24/24, 7:15 PM Collections Class in Java - GeeksforGeeks

18 List<String> l2 = new ArrayList<>();


19
20 // Add elements to l2
21 l2.add("Bat");
22 l2.add("Frog");
23 l2.add("Lion");
24
25 // Check if disjoint or not
26 System.out.println(
27 Collections.disjoint(l1, l2));
28 }
29 }

Output

true

Want to be a master in Backend Development with Java for building


robust and scalable applications? Enroll in Java Backend and
Development Live Course by GeeksforGeeks to get your hands dirty
with Backend Programming. Master the key Java concepts, server-side
programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or
want to be a Java Pro? This course equips you with all you need for
building high-performance, heavy-loaded backend systems in Java.
Ready to take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.

Comment More info Next Article


Collection Interface in Java

Similar Reads
Difference between Traditional Collections and Concurrent…
https://www.geeksforgeeks.org/collections-class-in-java/?ref=next_article 21/26

You might also like