Java Collections Framework Complete Tutorial

Java Collections framework

In this article, we will learn about one important feature of Java – Collections framework. Collections framework in Java is very commonly used and this is one the most asked topics in the Java interviews.

So let’s start learning :

Introduction to Java Collections Framework

A Collection simply is group of similar objects. Collections is a framework in Java. It provides an easy architecture for storing and manipulating group of objects.

Java Collections framework helps in performing various operations of group of data such as sorting, insertion, searching, deleting etc.

Java Collections framework / API consists of various classes and interfaces which helps in working with different types of data structures such as lists, queues, maps etc.

Java Collections framework consists of many ready to use classes which helps in dealing with group of homogeneous as well as heterogeneous objects.

What is a Collection in Java

A Collection in Java represents a group of objects.

What is a Framework in Java

Framework is very essentially used in all the programming languages. It provides a readymade architecture which makes it easy to use for developers. A framework is consists of classes and interfaces.

What is Collections framework

Java Collections framework simply represents a unified architecture which helps in storing and manipulating of group of objects.The Collection framework represents a unified architecture for storing and manipulating a group of objects.

Parts of Collections Framework in Java

Java Collections framework is consists of below parts :

  • Interfaces.
  • Classes.
  • Algorithms.

A) Interfaces

Java Collections Framework has various interfaces.

As we know, interfaces only provide definition and not implementation hence they are abstract. So Interfaces of Collections framework also provides the abstract data types to represent different collections.

The root interface of Collections framework in Java is java.util.Collection. Collection is the top in the Collection framework hierarchy.

Collection interface is provided in java.util package. Java Collection interface provides various important methods like add(), remove(), size(), iterate() etc.

List of Interfaces in Java Collections framework :

  • Collection
  • List
  • Set
  • Queue
  • Deque
  • SortedSet

Map is also an interface which is considered as part of Java Collections framework. It is provided in java.util package. Map interface is one and only interface in Java Collections framework which does not inherit from the Collection interface.

All Collections interfaces are present in java.util package.

B) Classes

Collections framework in Java contains implementation classes for Collections. These are the implementations of various Java Collections interfaces.

These classes however solves our core needs of programming but in case we need to extend the functionality of these classes, We can inherit these classes to create our own custom classes to handle the Collections.

Java Collections framework was introduced in Java verion 1.2 . In Java 1.5, many other Collection classes were also provided which are thread-safe.

These thread-safe classes can be used to modify the Collection while iterating the same. Some of these classes are ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet etc.

These thread-safe Java Collections classes are available in java.util.concurrent package.

List of Classes in Java Collections framework :

  • ArrayList
  • LinkedList
  • Vector
  • Stack
  • HashSet
  • LinkedHashSet
  • TreeSet
  • ArrayDeque
  • PriorityQueue

All the Collections framework classes are available in java.util and java.util.concurrent package.

C) Algorithms

Java Collections framework also contains algorithms which helps in performing various operations on group of objects like sorting, searching etc.

Hierarchy of Java Collections Framework

Below Diagram shows the Java Collections framework hierarchy :

Java Collections framework

Benefits of Java Collections Framework

Java Collections framework is widely used and has many benefits. Those are listed below :

  • Reduces the development effort – Java Collections framework drastically reduces the development effort. It provides many classes which helps in storing and manipulating data very easily. So developers can use these classes to manage data and objects and they do not need to design the APIs for this purpose.
  • Increased Quality – Quality of code is increased if we are using the Java Collections classes as they are efficient and optimized so it is better to use the Collections framework rather than direct data structures.
  • Reusability and Interoperability – Reusability and Interoperability is increased as we have predefined Collection classes, we can re use them again and again.

Java Collections Interfaces

All the interfaces of Java Collections framework are the core foundation of the framework.

All the Java Collections framework interfaces are Generic. E.g Collection interface declaration is public interface Collection<E>.

In Generics, <E> denotes the Generic type parameter , we use this to define the type of object the collection should contain.

All Interfaces in Collections API are declared as Generic to avoid the Run time errors by provide type safety to Objects.

In case of performing an unsupported operation, Collection implementation throws an UnsupportedOperationException.

Let’s learn all interfaces present in Collection Framework :

Collection Interface

Collection interface is the root / top interface in the Java Collection Framework hierarchy.

The Collection interface is implemented by all the classes of Collections framework.

All collection classes and interfaces have all the methods declared by the Collection interface. We can say that, The Collection interface builds the base for all the other Collections.

Java Collections framework

The Collection interface has many methods such as :

  • To get the number of elements of Collection.
  • To know if Collection is empty or not.
  • To add and remove elements from Collection.
  • To iterate over the Collection.
  • To perform bulk operations like adding all elements to one Collection etc.

Methods of Collection interface

MethodDescription
public boolean add(E e)This method inserts an element in this collection.
public boolean addAll(Collection<? extends E> c)This method inserts the specified collection elements in the invoking collection.
public boolean remove(Object element)This method deletes an element from the collection.
public boolean removeAll(Collection<?> c)This method deletes all the elements of the specified collection from the invoking collection.
default boolean removeIf(Predicate<? super E> filter)This method deletes all the elements of the collection that satisfy the specified predicate.
public boolean retainAll(Collection<?> c) This method deletes all the elements of invoking collection except the specified collection.
public int size() This method returns the total number of elements in the collection.
public void clear() This method removes the total number of elements from the collection.
public boolean contains(Object element) This method searches for an element in the collection.
public boolean containsAll(Collection<?> c)This method searches for the specified collection in the collection.
public Iterator iterator() This method returns an iterator.
public Object[] toArray() This method converts collection into array.
public <T> T[] toArray(T[] a) This method converts collection into array. Here, the runtime type of the returned array is that of the specified array.
public boolean isEmpty() This method checks if collection is empty.
default Stream<E> parallelStream() This method returns a possibly parallel Stream with the collection as its source.
default Stream<E> stream() This method returns a sequential Stream with the collection as its source.
default Spliterator<E> spliterator() This method generates a Spliterator over the specified elements in the collection.
public boolean equals(Object element) This method matches two collections.
public int hashCode() This method returns the hash code number of the collection.

Iterator Interface

Iterator interface , as the name suggests , provides various methods to iterate over any Collection.

This interface provides the methods to iterate over elements in the Collection but only in forward direction. We can use the iterator method to get the iterator instance from any Collection.

Iterator basically similar to Enumeration but Iterator is mainly used for Java Collections.

Iterator not only allows to iterate through element but it also have functionality to remove any element from Collection at the time of iteration.

Java Collections framework

Methods of Iterator interface

Iterator interface only contains below three methods :

MethodDescription
public boolean hasNext()It returns true if the iterator has more elements
otherwise it returns false.
public Object next()It returns the element and moves the cursor pointer
to the next element.
public void remove()It removes the last elements returned by the iterator.
It is less used.

Iterable Interface

The Iterable interface can be seen on top of the Collections framework hierarchy. The Iterable interface is implemented by the Java Collection interface so all the Collection interfaces also implement this interface.

Java Collections framework

Iterable interface does only contain one single abstract method :

MethodDescription
Iterator<T> iterator() This method is used to return the iterator
over the type T elements.

List Interface

List interface is very commonly and most used interface in Java Collections framework. It is the child or sub interface of Collection interface in Java.

It is based on data structure list that’s why it stored the ordered collection of object and It can contain duplicate elements.

List allows to access its element by using index. It is basically an array but with dynamic length.

ArrayList, LinkedList, Vector, and Stack classes implements the List interface.

Java Collections framework

List interface has various methods to perform various operations on its elements such as :

  • To add an element at a specific index in the list
  • To remove/replace element based on the index etc.

Collections class in Java provides various algorithms to perform operations on like – search, sort, reverse etc.

Below is the syntax to instantiate the List :

List <data-type> list=  new ArrayList();  
List <data-type> list = new Stack(); 
List <data-type> list = new LinkedList();  
List <data-type> list = new Vector();    

Set Interface

Set is one type of Collection which does not allow the duplicate elements. Set only allows one null value to store. Set Interface is present in java.util package.

This interface inherits the Collection interface.

Set contains unordered unique set of elements. In real life example, we can say Set is used to represnt deck of cards.

HashSet, LinkedHashSet and TreeSet are the implementation classes of Set interface.

Unlike List, Set does not allow random access of the elements in the Collection.

Java Collections framework

Below is the syntax to instantiate the Set :

Set<data-type> set = new HashSet<data-type>();  
Set<data-type> set = new TreeSet<data-type>();   
Set<data-type> set = new LinkedHashSet<data-type>();  

Queue Interface

Queue is a Collection which holds multiple elements prior to processing.

As like other Collections, Queue interface also extends the Collection interface. So Queue has all the methods provided by Collection interface.

In addition to that, Queue provides some more methods for insertion, inspection and extraction operations.

Java Collections framework

Queues typically store its element in First – In – First – Out manner Except the Priority Queue implementation of Queue as it supplies element in the original order of elements.

In a First-In-First-Out queue , new elements are added at the tail of queue.

Below is the syntax to instantiate the Queue:

Queue<Data-type> queue = new PriorityQueue();  
Queue<Data-type> queue = new ArrayDeque();   

Deque Interface

Deque interface in Java Collections framework extends the Queue interface. Deque is a considered as linear Collection. Deque is short form of Double_Ended-Queue.

In Deque, elements can be inserted and removed from both the ends.

Deque is usually pronounced as deck. Deque interface has various methods that allows the elements to be inserted and accessed from both the ends.

Most of the Deque implementation have no limitations of number of elements to be stored But this interface supports those deque as well which are capacity restrcited.

Deque provides methods to inserting, removing and examining the elements.

Java Collections framework

Below is the syntax to instantiate the Deque:

 Deque deque = new ArrayDeque();  

Map Interface

Map is an interface in Java Collections framework. However it does not extend the Java Collection interface.

Map interface stores the elements in key and value format. Map cannot stores any duplicate keys but values can be duplicate means each unique key can map to maximum one value.

HashMap, LinkedHashMap and TreeMap are the implementation classes of Map interface.

Map has some basic operations like get, put, size, isEmpty etc.

Java Collections framework

Below is the syntax to instantiate the Map:

Map< Data-type , Data-type> hm =  new HashMap< Data-type , Data-type>();

SortedSet Interface

As we know, Set interface does not provide ordering of its elements. So SortedSet is the interface used as the alternative of Set interface when the total ordering of elements is required.

SortedSet is a Set which arranges its elements in increasing order.

SortedSet additionally provides several methods for natural ordering of the elements.

Real life example of SortedSet can be : Word lists.

TreeSet is the implementation class of SortedSet interface.

Java Collections framework

Below is the syntax to instantiate the SortedSet:

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

ListIterator Interface

ListIterator interface is basically an iterator for Collections. It allows to traverse the elements of Collections in both the directions : Forward and Backward.

We can also perform many operations during iterating the Collections such as modify the list elements, get the current position of the iterator in the list etc.

ListIterator never has any current element as the cursor position of this iterator lies between the two elements which are :

  • the element which will get by calling previous() method and
  • the element which will get by calling the next() method.
Java Collections framework

How to use ListIterator :

ListIterator<E> listIterator() 

SortedMap Interface

SortedMap is a Map which maintains the ordering of its elements. It maintains the ascending order. It is basically a Map implementation of SortedSet.

Sorted maps maintains its key/value pair elements natural order such as telephone directories.

Java Collections framework

Example to use SortedMap :

SortedMap<Integer, String> sm = new TreeMap<Integer, String>();

Java Collections Classes

In the previous section, we have learnt all the interfaces present in Java Collections framework.

Java Collections framework has many implementation classes for those interfaces as well and these are widely used.

Some of most used implementation classes are ArrayList, HashMap and HashSet which are the implementations of List, Map and Set interface respectively.

Some thread-safe concurrent classes were also introduced in Java version 1.5 in the Java Collections framework which are ConcurrentHashMap etc.

Let’s learn important classes present in Java Collections Framework :

ArrayList Class

The ArrayList in Java is the implementation class for List interface in Java Collections framework. It is one of the most used class in Java Collections.

The underlying data structure behind ArrayList is array but dynamic in size. It is like a resizable array.

The ArrayList class is the implementation of List interface thus it also maintains the insertion order of elements and duplication is also allowed. Null values are permitted in an ArrayList.

It implements all the operations, methods provided by the List interface like getting an element through index etc.

ArrayList class in Java is non-synchronized that means it is not thread-safe.

The operations of ArrayList like size, set, get, isEmpty, iterator, and list iterator run in constant time. However, The add operation runs in the amortized constant time i.e. O(n) time.

If we compare to LinkedList then the constant factor is low compared to LinkedList.

Simple Example of ArrayList in Java :


import java.util.*;

class ArrayListExample {

public static void main(String args[]) {

    //Creating an ArrayList of String
    ArrayList < String > al = new ArrayList < String > ();

    //Add the elements into ArrayList
    al.add("Tech");  
    al.add("Blog");
    al.add("Station");

    //Iterate through ArrayList


    Iterator itr = al.iterator();

    while (itr.hasNext()) {
        System.out.println(" "+itr.next());
    }
   }
}

LinkedList Class

LinkedList class in Java is the implementation of List and Deque interfaces in Java Collections framework.

The underlying data structure for LinkedList class is Doubly linked list.

It maintains the insertion order and it allows duplicate and null values. LinkedList is a non-synchronized class hence it is not thread-safe.

It implements all the operations provided by the List interface.

If comparing to ArrayList, LinkedList provides faster manipulation of its elements as ArrayList requires a lot of shifting for any manipulation.

Simple Example of LinkedList in Java :

import java.util.*;

class LinkedListExample {

public static void main(String args[]) {

    //Creating an ArrayList of String
    LinkedList < String > list = new LinkedList < String > ();

    //Add the elements into ArrayList
    list.add("Tech");  
    list.add("Blog");
    list.add("Station");

    //Iterate through LinkedList


    Iterator itr = list.iterator();

    while (itr.hasNext()) {
        System.out.println(" "+itr.next());
    }
   }
}

Further reading –

Vector class

Vector is the implementation class for List interface in Java Collections framework. Vector is similar to ArrayList with very less differences.

Vector in Java also uses the dynamic array to store the elements.

Vector does allow duplicate elements and provides insertion order of processing.

Vector is same as ArrayList except vector is synchronized means thread-safe. It has additional methods that are not part of Collection framework.

Simple Example of Vector in Java :

import java.util.*;

public class VectorExample {
    
    public static void main(String args[]) {
        
        //Creating Vector of Strings
        Vector < String > v = new Vector < String > ();
        
        //Adding elements to Vector
        v.add("Tech");
        v.add("Blog");
        v.add("Station");
        
        //Iterating over Vector
        Iterator < String > itr = v.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Stack Class

The stack class in Java is the subclass of Vector in Java Collections framework.

Stack basically implements LIFO i.e Last In First Out data structure.

As Stack is child class of Vector, it has all the methods provided by the Vector class with additional methods of its own like push(), peek() etc.

Simple Example of Stack in Java :

import java.util.*;

public class StackExample {
    
    public static void main(String args[]) {
        
        
        //Creating Stack
        Stack < String > stack = new Stack < String > ();
        
        //Adding elements to Stack
        stack.push("Tech");
        stack.push("Blog");
        stack.push("Station");
        
        //Removing element from Stacl
        stack.pop();
        
        //Iterating through Stack
        Iterator < String > itr = stack.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

HashMap Class

HashMap is the implementation class for Map interface in the Java Collections framework. It is a implementation based on Hash Table.

HashMap allows the null key and null values. Only one null key and multiple null values are allowed in HashMap.

HashMap does not guarantee for any ordering. HashMap is a non-synchronized class hence it is not thread-safe.

We can set the initial capacity and the load factor for the HashMap using its constructors.

Simple Example of HashMap in Java :

import java.util.*;

class HashMapExample {
    
    public static void main(String args[]) {
        
        //Creating HashMap
        
        HashMap < Integer, String > map = new HashMap < Integer, String > ();
        
        //Adding values to HashMap
        map.put(1, "Tech");
        map.put(2, "Blog");
        map.put(3, "Station");

        //Iterating over HashMap
        for (Map.Entry entry: map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }
}

TreeMap Class

TreeMap in Java is also a implementation class for Map interface. It is a implementation based on the read-black tree. It is a NavigableMap.

TreeMap in Java Collections framework is a ordered Map. By default, The elements in TreeMap are sorted in natural order of its keys.

We can also use Comparator at the time of TreeMap creation and change the ordering criteria.

TreeMap is a non-synchronized collection hence it is not thread-safe.

The operations such as get, remove, put, containsKey in TreeMap costs log(n) time.

Simple Example of TreeMap in Java :

import java.util.*;

class TreeMapExample {
    
    public static void main(String args[]) {
        
        //Creating TreeMap
        
        TreeMap < Integer, String > map = new TreeMap < Integer, String > ();
        
        //Adding values to TreeMap
        map.put(1, "Tech");
        map.put(2, "Blog");
        map.put(3, "Station");

        //Iterating over TreeMap
        for (Map.Entry entry: map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }
}

HashSet Class

HashSet in Java is the basic implementation class for Set interface and is backed by a HashMap.

The ordering of element is not guaranteed in the HashSet class of Java Collections framework.

It only allows the unique elements and also null value is allowed in HashSet.

It is allowed that we can define the initial capacity of HashSet and the load factor.

It provides constant time performance for HashSet basic operations like size, remove and contains.

Simple Example of HashSet in Java :

import java.util.*;

class HashSetExample {
    
    public static void main(String args[]) {
        
        
        //Creating the HashSet of Strings
        
        HashSet < String > set = new HashSet();
        
        //Adding elements into HashSet
        set.add("Tech");
        set.add("Blog");
        set.add("Station");
        
        //Iterating over HashSet
        Iterator < String > itr = set.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

TreeSet Class

TreeSet is the implementation class for Set in Java Collections framework. It is basically a NavigableSet based on a TreeMap.

TreeSet provides natural ordering of its elements or we can modify the ordering using Comparator at the time of TreeSet creation.

TreeSet does not allow duplication of its elements.

The basic operation in TreeSet such as add, contains and remove costs log(n) time.

Simple Example of TreeSet in Java :

import java.util.*;

class TreeSetExample {
    
    public static void main(String args[]) {
        
        
        //Creating the TreeSet of Strings
        
        TreeSet< String > set = new TreeSet();
        
        //Adding elements into TreeSet
        set.add("Tech");
        set.add("Blog");
        set.add("Station");
        
        //Iterating over TreeSet
        Iterator < String > itr = set.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

LinkedHashSet Class

LinkedHashSet is the implementation class for Set interface in Java Collections framework. LinkedHashSet basically represents the LinkedList implementation of Set Interface.

LinkedHashSet class extends the HashSet class and it implements the Set interface.

Similar to HashSet, It does not allow duplicate elements and Similar to LinkedList, It maintains the insertion order of its elements and allow the null values.

Simple Example of LinkedHashSet in Java :

import java.util.*;

class LinkedHashSetExample {
    
    public static void main(String args[]) {
        
        
        //Creating the LinkedHashSet of Strings
        
        LinkedHashSet< String > set = new LinkedHashSet();
        
        //Adding elements into LinkedHashSet
        set.add("Tech");
        set.add("Blog");
        set.add("Station");
        
        //Iterating over LinkedHashSet
        Iterator < String > itr = set.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

PriorityQueue Class

PriorityQueue is the implementation class for Queue interface in Java Collections framework.

As we know, Queue processes its elements in the FIFO order but if we want to change the ordeing criterai such that elements should be processed based on their priorities. We can use PriorityQueue.

We need to use the Comparator while creating the PriorityQueue.

PriorityQueue does not allow null elements.

Simple Example of PriorityQueue in Java :

import java.util.*;

class PriorityQueueExample {
    
    public static void main(String args[]) {
        
        //Creating PriorityQueue of String
        PriorityQueue < String > queue = new PriorityQueue < String > ();
        
        //Adding elements into PriorityQueue
        queue.add("Tech");
        queue.add("Blog");
        queue.add("Station");
        
        
        System.out.println("head of the queue :" + queue.element());
        System.out.println("head of the queue :" + queue.peek());
       
        //Iterating over the PriorityQueue
        Iterator itr = queue.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
        queue.remove();
        queue.poll();
        System.out.println("removal of two elements:");
        
        Iterator < String > itr2 = queue.iterator();
        while (itr2.hasNext()) {
            System.out.println(itr2.next());
        }
    }
}

ArrayDeque class

ArrayDeque class is the implementation class for Deque interface in Java Collections framework.

It allows its elements to be added and deleted from both the ends.

ArrayDeque does not have any Capacity restrictions. ArrayDeque is faster in comparison with the ArrayList and Stack.

Simple Example of ArrayDeque in Java :

import java.util.*;

public class ArrayDequeExample {
    
    public static void main(String[] args) {
        
        
        //Creating the Deque
        Deque < String > deque = new ArrayDeque < String > ();
        
        //Adding the elements into Deque
        deque.add("Tech");
        deque.add("Blog");
        deque.add("Station");
        
        
        //Iterating the elements  
        for (String str: deque) {
            System.out.println(str);
        }
    }
}

Conclusion

In this article, we have learnt about Java Collections framework, Its different interfaces and classes with examples.

Leave a Reply

Your email address will not be published. Required fields are marked *