Java Collections Example | Collections in Java

Java Collections Framework was introduced by the J2SE 1.2. It was introduced to standardize how groups of objects are handled. Before the release of the Collections Framework, Java provided the use of ad hoc classes such as Dictionary, Vector, Stack, and Properties to work with groups of objects. These provided a challenge that they were all handled in different ways, i.e., there was no standardization in the way groups of objects handled.

Let’s see the Java Collections Tutorial With Example.

See the following figure.

Java Collections Tutorial With Example

Java Collections  Example

Java collection is the group of individual objects represented as a single unit. The Collections Framework was thus introduced to deal with the problem of standardization. This framework has several useful classes that have tons of useful functions that makes a programmer task super straightforward.

Java Collections can achieve all the functions that you perform on data such as searching, sorting, insertion, manipulation, and deletion.

#Advantages of Collection Framework

  1. Consistent API: An API has the basic set of interfaces like Collection, Set, List, or Map. All classes (ArrayList, LinkedList, Vector, etc.) that implement these interfaces have some standard set of methods.
  2. Reduces programming effort: A programmer doesn’t have to worry about the design of Collection, and he can focus on its best use in his program.
  3. Increases program speed and quality: Increases performance by providing high-performance implementations of useful data structures and algorithms.

#The Collection Interfaces 

Several core interfaces are defined by the Collections Framework, such as:

  1. CollectionTop of the collections hierarchy. Used to work with the groups of objects.
  2. Deque Extends Queue to work with the double-ended queue.
  3. List – Extends Collection to work with the lists of objects.
  4. NavigableSet – Extends SortedSet to work with the retrieval of elements which are based on the closest-match searches.
  5. Queue – Extends Collection to work with a queue which follows the FIFO principle.
  6. Set – Extends Collection to work with the sets containing unique elements.
  7. SortedSet – Extends Set to work with a sorted sets.

As an example, the List interface is declared as the following.

interface List<O>

Here,  O specifies the type of objects that the list will be working with.

Note: All other Collection Interfaces are declared in the same manner.

#Collection Classes

The Collection Classes are the standard classes that implement the Collection Interfaces. Generally, Collection Classes are not synchronized, but it is possible, by some modification, to achieve synchronization as well.

The main collection classes are as below:

  1. AbstractCollection – Implements most of the Collection interface.
  2. AbstractList –  Extends AbstractCollection and implements most of the List interface.
  3. AbstractQueue – Extends AbstractCollection and implements parts of the Queue interface.
  4. AbstractSequentialList– Extends AbstractList and uses sequential rather than random access of its elements.
  5. LinkedList – Extends AbstractSequentialList to implement a linked list.
  6. ArrayList – Extends AbstractList to implement a dynamic array.
  7. ArrayDeque – Extends AbstractCollection and implements the Deque interface to implement a dynamic double-ended queue.
  8. AbstractSet – Extends AbstractCollection and implements most of the Set interface.
  9. EnumSet – Extends AbstractSet to work with enum elements.
  10. HashSet – Extends AbstractSet to work with a hash table.
  11. LinkedHashSet – Extends HashSet to perform insertion-order iterations.
  12. PriorityQueue – Extends AbstractQueue to implement a priority based queue.
  13. TreeSet – Extends AbstractSet to implement a set stored in a tree.

Note: Several legacy classes, in addition to the collection classes, have been altered to support collections. Some of these legacy classes are – Stack, Vector, and Hashtable.

#Methods of Collection interface in Java

There are many methods declared in the Collection interface. All the methods are as follows.

No. Method Description
1 public boolean add(E e) It is used to insert the item in this collection.
2 public boolean addAll(Collection<? extends E> c) It is used to insert a specified collection items in the invoking collection.
3 public boolean remove(Object element) It is used to delete the item from the collection.
4 public boolean removeAll(Collection<?> c) It is used to delete all the items of the specified collection from the invoking collection.
5 default boolean removeIf(Predicate<? super E> filter) It is used to delete all the items of the collection that satisfy the specified predicate.
6 public boolean retainAll(Collection<?> c) It is used to delete all the items of invoking collection except the specified collection.
7 public int size() It returns the total number of items in the collection.
8 public void clear() It removes the total number of items from the collection.
9 public boolean contains(Object element) It is used to search for an item.
10 public boolean containsAll(Collection<?> c) It is used to search a specified collection in the collection.
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts the collection into the array.
13 public <T> T[] toArray(T[] a) It converts the collection into an array. Here, the runtime type of a returned array is that of a specified array.
14 public boolean isEmpty() It checks if a collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with a collection as its source.
16 default Stream<E> stream() It returns a sequential Stream with a collection as its source.
17 default Spliterator<E> spliterator() It generates the Spliterator over the specified items in the collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of the collection.

#List Interface

List interface is the child interface of the Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use it.

List <data-type> list1= new ArrayList();  
List <data-type> list2 = new LinkedList();  
List <data-type> list3 = new Vector();  
List <data-type> list4 = new Stack();

There are various methods in the List interface that can be used to insert, delete, and access the elements from the list. The classes that implement the List interface are given below.


In Java, arrays are of a fixed length, i.e., they cannot increase or decrease in size once they are declared. It makes it essential to know in advance how many elements are needed to be stored in the array. However, there are situations in which this is not possible, which creates the needed for dynamic arrays. ArrayList supports dynamic arrays that can grow or shrink when needed.


import java.util.*;

class Example1{
	public static void main(String [] args){
		ArrayList<String> a = new ArrayList<String>();

		System.out.println("Initial size: " + a.size());


		System.out.println("ArrayList: " + a);
		System.out.println("Size: " + a.size());

		a.remove(2); //removes from index 2
		a.remove("B");//finds and removes "B"
		a.add(2, "V"); //adds "V" at index 2

		System.out.println("ArrayList: " + a);
		System.out.println("Size: " + a.size());


See the below output.

Java ArrayList


The LinkedList class implements the linked-list data structure. Since it implements the List interface, add(O) appends items(object references) to the end of the list, in the same way, addLast(O) does. To insert items at a specific location, we use the add( int, O ) form of add(), as illustrated in the example below.

As LinkedList also implements the Deque interface, one has access to the methods defined by Deque. To add elements at the start of the list or end of the list, addFirst()  or addLast() can be used. In the same way, to remove elements from the start or end of the list, removeFirst() or removeLast() can be used. See the following program.


import java.util.*;

class Example2{
	public static void main(String [] args){
		LinkedList<String> l = new LinkedList<String>();



		l.add(6, "&");

		System.out.println("Contents of LinkedList: " + l);


		System.out.println("Contents of LinkedList: " + l);


		System.out.println("Contents of LinkedList: " + l);

See the following output.


The HashSet class creates a collection that uses a hash table for storing items in the collection. A hash table stores items by a mechanism known as hashing.  The informational content of the key is used to create a unique value called a hash code. The hash code is then used as an index to store the data associated with the key.

The advantage of hashing is that the execution time for methods such as add() and remove() remains constant even for large sets.


import java.util.*;

class Example3{
	public static void main(String [] args){
		HashSet<String> h = new HashSet<String>();



See the output.

In conclusion, the Java Collections Framework is similar to the Standard Template Library(STL) of C++ in spirit. However, significant differences exist between the two.


Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.

Consider the following example.

import java.util.*;  
public class TestJavaCollection {  
  public static void main(String args[]) {  
      Vector<String> v=new Vector<String>();  
      Iterator<String> itr=v.iterator();  
      while (itr.hasNext()) {

See the following output.



The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Consider the following example.

import java.util.*;  
public class TestJavaCollection {  
public static void main(String args[]) {  
      Stack<String> stack = new Stack<String>();  
      Iterator<String> itr=stack.iterator();  
      while(itr.hasNext()) {  

See the following output.

Stack in Java

#Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as the following.

Queue<String> q1 = new PriorityQueue();  
Queue<String> q2 = new ArrayDeque();

#Set Interface

Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered set of elements which doesn’t allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

The set can be instantiated as follows.

Set<data-type> s1 = new HashSet<data-type>();  
Set<data-type> s2 = new LinkedHashSet<data-type>();  
Set<data-type> s3 = new TreeSet<data-type>();

#SortedSet Interface

SortedSet is the alternate of the Set interface that provides a total ordering on its elements. The elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as follows.

SortedSet<data-type> set = new TreeSet();


Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.

Consider the following example.

import java.util.*;  
public class TestJavaCollection {  
public static void main(String args[]) {  
      //Creating and adding elements  
      TreeSet<String> set=new TreeSet<String>();  
      //traversing elements  
      Iterator<String> itr=set.iterator();  
      while(itr.hasNext()) {  

See the output.

TreeSet in Java
Finally, Java Collections Example is over.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.