Collection Framework Overview

The Collection Framework in Java is a collection of interfaces and classes to store, process and transfer the data efficiently. 

The Collection Framework in Java is used to represent group individual objects as a single entity.

Where we use Collection Framework in Projects?

In projects, it is very common to use collection framework where ever we need to deal with group of objects. Let us look into following image which explains searching functionality of products on e-commerce website.

Usage Of Java Collection Framework

As per above image, User is searching for products in e-commerce website with ‘Name’, ‘Min Price’, ‘Max Price’ attributes. Then the request will go to Controller -> Service -> Repository -> Database. The database returned results we are storing into collection object, transfer(return) those collection object from repository to service, In service we are processing(filter) data as per user needs then transferring(return) to controller then transfer to UI. So for storing, processing and transferring we are using collection object.

NOTE: In the above example, in the place of List<Product> we can use array(Product[]), But arrays has size limitation and there is no pre-defined method support for data processing(search, sort, filter … etc.) in arrays.

Hence, Where ever there is a need of storing, processing, transferring group of objects then we should go for Collection Framework.

Hierarchy of Collection Framework

The java.util package contains all the classes and interfaces for the Collection framework. Let us see the hierarchy of Collection framework. 

Java-Collection-Framework-Hierarchy
Java-Collection-Framework-Hierarchy

key interfaces of collection framework

Collection framework has defined several interfaces and classes to deal with different kind of data sets

The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes

The utility package, (java.util) contains all the classes and interfaces that are required by the collection framework

Iterable

  • Iterable is the root interface for the entire collection framework
  • The main functionality of this interface is to provide an iterator for the collections
  • This interface contains only one abstract method which is the iterator() which returns Iterator object.

Collection

  • Collection interface extends the Iterable interface
  • It declares basic methods that every Collection should have
  • This interface builds a foundation for all Collection implemented classes
  • There is no concrete class which implement Collection interface directly
METHODDESCRIPTION
public boolean add(E e) To insert an element in this collection at the end
public boolean addAll(Collection c) To insert the specified collection elements on
invoking collection at the end
public boolean remove(Object element) To delete an element from the collection
public boolean removeAll(Collection c) To delete all the elements of the specified collection from the invoking collection
default boolean removeIf(Predicate filter) To delete all the elements of the collection that satisfy the specified predicate.
public boolean retainAll(Collection c) To delete all the elements of invoking collection except the specified collection
public int size() Returns the total number of elements in the collection
public void clear() Removes all the elements from the collection
public boolean contains(Object element) To check existence of the given element in the collection
public boolean containsAll(Collection c) To check existence of the given collection on the invoking collection
public Iterator iterator() Returns an Iterator which is used to loop over the collection, It is inherited method from Iterable interface.
public Object[] toArray() Converts collection into array
public T[] toArray(T[] a) Converts collection into array. Here, the runtime type of the returned array is that of the specified array
public boolean isEmpty() Checks if collection is empty
default Stream parallelStream() Returns a possibly parallel Stream with the collection as its source
default Stream stream() Returns a sequential Stream with the collection as its source
default Spliterator spliterator() Generates a Spliterator over the specified elements in the collection
public boolean equals(Object element) To compare two collections for equality
public int hashCode() Returns the hash code number of the collection

List

  • List is a child interface of the Collection interface
  • Insertion order is preserved
  • Duplicate objects are allowed
  • List interface has methods to perform position based operations
  • The position-oriented operations include the ability to insert an element, get an element, as well as remove or change an element at the desired position.
  • List interface is implemented by classes ArrayList, LinkedList, Vector, and Stack
METHODDESCRIPTION
void add(int index, E element) To insert the specified element at the specified position in a list
boolean add(E e) To append the specified element at the end of a list
boolean addAll(Collection c) To append all of the elements in the specified collection to the end of a list
void clear() To remove all of the elements from this list
boolean equals(Object o) To compare the specified object with the elements of a list
int hashcode() To return the hash code value for a list
E get(int index) To fetch the element from the particular position of the list
boolean isEmpty() Returns true if the list is empty, otherwise false
int lastIndexOf(Object o) To return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element
Object[] toArray() To return an array containing all of the elements in this list in the correct order
T[] toArray(T[] a) To return an array containing all of the elements in this list in the correct order
public boolean contains(Object element) To check existence of the given element in the list
public boolean containsAll(Collection c) To check existence of the given collection on the invoking list
public Iterator iterator() Returns an Iterator which is used to loop over the list, It is inherited method from Iterable interface.
int indexOf(Object o) To return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element
E remove(int index) To remove the element present at the specified position in the list
boolean remove(Object o) To remove the first occurrence of the specified element
boolean removeAll(Collection c) To remove all the elements from the list
void replaceAll(UnaryOperator operator) To replace all the elements from the list with the specified element
void retainAll(Collection c) To retain all the elements in the list that are present in the specified collection
E set(int index, E element) To replace the specified element in the list, present at the specified position
void sort(Comparator c) To sort the elements of the list on the basis of specified comparator
Spliterator spliterator() To create spliterator over the elements in a list
List subList(int fromIndex, int toIndex) To fetch all the elements lies within the given range
int size() To return the number of elements present in the list

We can instantiate the List object with any of it’s implemented classes as follows.

Java Collection Framework List Interface Hierarchy

ArrayList

  • ArrayList class implements the List interface
  • ArrayList underlying data structure is resizable array or grow able array
  • Insertion order is preserved
  • Duplicate objects are allowed
  • null insertion is possible
  • ArrayList class is non synchronized

Output :

nameList : [Sekhar Reddy, Tanvika, Mounika]

  • Collections class defines the following method to get synchronized version of any List object
  • ArrayList implements Serializable and Clonable interfaces to support serialization and cloning
  • ArrayList and Vector implements RandomAccess interface so that we can access any element randomly with the same speed
  • ArrayList is best choice, if our requirement is  frequent retrieval operation
  • ArrayList is the worst choice if our requirement is frequent adding or removing elements based on the index because shifting is required

LinkedList

  • LinkedList class implements the List interface
  • Underlying data structure is doubly linked list
  • Insertion order is preserved
  • Duplicate objects are allowed
  • null insertion is allowed
  • LinkedList class is non synchronized

Output :

nameList : [Sekhar Reddy, Tanvika, Mounika]

  • Collections class defines the following method to get synchronized version of any List object
  • LinkedList class implements Serializable an Cloneable interfaces but not RandomAccess
  • In general LinkedList class can be used for implementing Stacks and Queues. To support this type of requirement LinkedList contains the following six specific methods
  1. void addFirst(Object o);
  2. void addLast(Object o);
  3. Object removeFirst();
  4. Object removeLast()
  5. Object getFirst()
  6. Object getLast();
  • LinkedList is the Best choice if our requirement is frequent insertion or deletion or modification based on the position because no shifting is required
  • LinkedList worst choice if frequent operation is retrieval

Vector

  • Vector class implements the List interface
  • It is a legacy collection class
  • Underlying data structure is Resizable array or grow able array
  • Insertion order is preserved
  • Duplicate objects are allowed
  • null insertion is possible
  • Vector class is synchronized

Output :

namesVector : [Sekhar Reddy, Tanvika, Mounika]

  • Vector class implements Serializable, Clonable, RandomAccess, List and Collection interfaces
  • Vector is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.
  • For adding objects
    • Void add(Object obj) //from Collection
    • Void add(int index, Object o) // form List
    • Void addElement(Object obj) // from Vector
  • For removing elements.
    • Object remove(Object o) // Collection
    • Object remove(int index) // List
    • Object removeElement(Object o) // Vector
    • Object removeElementAt(int index) //Vector
    • Object clear() //Collection
    • removeAllElements() //Vector
  • For retrieving Objects
    • Object get(int index) //List
    • Object elementAt(int index) //Vector
    • Object firstElement()//Vector
    • Object lastElement() //Vector
  • Other common methods
    • Int capacity()//Vector
    • Int size() //Collection
    • Enumeration elements() //Vector
  • Vector is best choice, if our requirement is  frequent retrieval operation
  • Vector is the worst choice, if our requirement is frequent adding or removing elements based on the index because shifting is required
  • Every method is synchronized hence Vector object by default thread safe

ArrayList Vs Vector

ArrayListVector
No method is synchronizedEvery method is synchronized
ArrayList is not Thread safeVector is thread safe
Performance is high than VectorPerformance is low than ArrayList
It was introduced in 1.2 version and it is non-legacy It was introduced in 1.0 version and it is legacy

Stack

  • Stack is the child of Vector, It contains only one constructor
    • Stack stack = new Stack();
  • Stack follows LIFO(Last In First Out)
  • The Stack contains all of the methods of Vector class and also provides its own methods
  • Object push(Object obj)
    • Insert an object into the stack at the end
  • Object pop();
    • To remove and returns top element of the stack.
  • Object peek();
    • To return top of the stack without removal
  • boolean empty()
    • Returns true if the stack is empty otherwise returns false
  • int search(Object obj)
    • Returns offset of the element if it is available. Otherwise it returns -1.

Output :

namesStack : [Sekhar Reddy, Tanvika, Mounika]
Stack Top Element: Mounika

Set

  • Set is child interface of Collection
  • Set doesn’t have methods, All methods are inherited from Collection
  • Duplicate objects are not allowed
  • Insertion order not preserved
  • We can store at most one null value in Set
  • Set interface implemented by classes HashSet, LinkedHashSet and TreeSet.

We can instantiate the Set object with any of it’s implemented classes as follows.

HashSet

  • HashSet class implements  Set interface
  • HashSet underlying data structure is hashtable
  • Duplicates objects are not allowed. If we are trying to insert any duplicate object we won’t get any compile time or runtime errors. But add() method simply returns false.
  • Insertion order is not preserved because it is based on hashCode() of the objects
  • HashSet implements Serializable and Clonable interface
  • HashSet is best suitable to perform search operations
  • null insertion is possible, But not advisable

Output :

HashSet elements : [CC, BB, DD, ZZ, AA]
Duplicate ‘ZZ’ element added ? : false
After dupliate added, HashSet elements : [CC, BB, DD, ZZ, AA]

LinkedHashSet

  • LinkedHashSet is the child class of HashSet
  • Insertion order is preserved
  • Duplicates objects are not allowed
HashSetLinkedHashSet
Insertion is not preservedInsertion is preserved
Underlying data structure is HashtableUnderlying data structure is combination of LinkedList and HashTable
Introduced in 1.2 versionIntroduced in 1.4 version
  • In the above HashSetDemo program if we replace HashSet with LinkedHashSet, elements will be inserted in “insertion oreder”

Output :

LinkedHashSet elements : [CC, DD, AA, BB, ZZ]
Duplicate ‘ZZ’ element added ? : false
After dupliate added, LinkedHashSet elements : [CC, DD, AA, BB, ZZ]

  • LinkedHashSet  and LinkedHashMap classes are best suitable to implement cashing applications where duplicates are not allowed

SortedSet

  • SortedSet is the child interface of Set
  • SortedSet elements are arranged in some order (ascending/descending) order
  • SortedSet provides the additional methods that inhibit the natural ordering of the elements
  • TreeSet class implements SortedSet interface

We can instantiate the SortedSet object with any of it’s implemented classes as follows.

NavigableSet

  • NavigableSet is the child interface of SortedSet
  • NavigableSet declares several methods for navigation purposes
  • TreeSet class implements NavigableSet interface

We can instantiate the NavigableSet object with any of it’s implemented classes as follows.

Java Collection Framework Set interface Hierarchy

TreeSet

fkjdflskfj

Queue

  • Queue is the child interface of Collection
  • Queue interface maintains the FIFO(first-in-first-out) order
  • Queue is used to hold the elements which are about to be processed
  • Queue interface implemented by classes PriorityQueue and ArrayDeque

We can instantiate the Queue object with any of it’s implemented classes as follows.

Deque

  • Deque is the child interface of Queue
  • Deque also known as a double-ended queue
  • Deque allow us to add and remove the elements from both the ends of the queue
  • Deque interface implemented by class ArrayDeque

We can instantiate the Deque object with any of it’s implemented classes as follows.

Java-Collection-Framework-Queue-Hierarchy
Java Collection Framework Queue interface Hierarchy

Map

  • All the above interfaces(Collection, List, Set, SortedSet, NaviagableSet and Queue) can be used to represent group of individual objects.
  • If we want to represent a group of objects as key value pairs then we should go for Map interface
  • Map is not child interface of Collection
  • Map keys are unique but values can be duplicate
  • Map interface implemented by classes HashMap, LinkedHashMap, TreeMap, WeakHashMap, IdentityHashMap, HashTable and Properties

We can instantiate the Map object with any of it’s implemented classes as follows.

SortedMap

  • SortedMap is the child interface of Map
  • SortedMap key elements are arranged in some order (ascending/descending) order
  • SortedMap provides the additional methods that inhibit the natural ordering of the key elements
  • SortedMap interface implemented by class TreeMap

We can instantiate the SortedSet object with any of it’s implemented classes as follows.

NavigableMap

  • NavigableMap is the child interface of SortedMap
  • NavigableMap declares several methods for key navigation purposes
  • NavigableMap interface implemented by class TreeMap

We can instantiate the NavigableMap object with any of it’s implemented classes as follows.

Java Collection Framework Map interface Hierarchy

Types of cursors

  • If we want to retrieve the objects of a Collection one by one we should go for cursors. There are three types of Cursors available in java.
    • Enumeration
    • Iterator
    • ListIterator

Enumeration

  • Enumeration interface is unidirectional cursor
  • Enumeration is applicable only for legacy collection classes(Stack, Vector, HashTable)
  • We can get Enumeration object by using elements() method of Vector
    • Enumeration e= vector.elements()
  • Enumeration interface defines the following two methods.
    • public boolean hasMoreElements()
    • public Object nextElement()

Output :

namesVector : [Sekhar Reddy, Tanvika, Mounika]
name: Sekhar Reddy
name: Tanvika
name: Mounika

  • Enumeration concept is applicable only for legacy classes and hence it is not a universal cursor
  • While performing iteration we are not allowed to add/remove/update elements of the collection. i.e. Enumeration read only cursor
  • To overcome these limitation Iterator was introduced

The implementation class of Enumeration is anonymous class

Iterator

  • Iterator interface is unidirectional cursor
  • Iterator is applicable for all collection classes, Hence it is universal cursor
  • We can get Iterator object by using iterator() method of java.lang.Iterable interface which is root interface of all collection classes
    • Iterator iterator = anyCollectionObject.iterator();
  • Iterator interface defines the following three methods 
    • public  boolean hasNext();
    • public Object next();
    • pulbic void remove();

Output :

namesList : [Sekhar Reddy, Tanvika, Mounika]
name: Sekhar Reddy
name: Tanvika
name: Mounika
namesList : [Sekhar Reddy, Tanvika]

  • Using remove() method of Iterator, we can remove the elements from the collection object
  • While performing iteration we can perform only read and removal operations, there is no chance of performing add/modify elements in collection. To overcome these limitation ListIterator was introduced

The implementation class of Iterator is Itr, which is an inner class in AbstractList

ListIterator

  • ListIterator interface is the child interface of Iterator
  • ListIterator interface is bi-directional cursor
  • ListIterator applicable only for List interface implemented classes
  • We can get ListIterator object by using listIterator() method of List interface
    • Iterator iterator = anyCollectionObject.iterator();
  • Iterator interface defines the following three methods 
    • public  boolean hasNext();
    • public Object next();
    • public int nextIndex();
      • If there is no next element it returns size of the list but not -1.
    • public boolean hasPrevious();
    • public Object previous();
    • public  int previousIndex();
      • If there is no previous element then this method returns -1.
    • public void remove();
    • public void add(Object newObj);
    • public void set(Object newObj);

Output :

Before Iteration namesList : [Sekhar Reddy, Tanvika, Mounika]
name: Sekhar Reddy
name: Tanvika
name: Mounika
After Iteration namesList : [Mr. Sekhar Reddy, Tanvika, KesavaReddy]

  • While performing iteration we can perform add/remove/modify elements of List implemented classes
  • It is most powerful cursor, But it is applicable for only List implemented class objects.

The implementation class of ListIterator is ListItr, which is an inner class in AbstractList

Enumeration vs Iterator vs ListIterator

PropertiesEnumeration Iterator ListIterator
Is it LegacyYesNoNo
It is Applicable forOnly legacy classesAny Collection ObjectAny List object
MovementSingle direction(forward)Single direction(forward)Bidirectional
How to getlegacyCollection
Object.elements();
anyCollection
Object.iterator();
listCollection
Object.listIterator();
Accessibilityread onlyread and removeread/add/remove/modify
Implementation classAnonymus classItrListItr
MethodshasMoreElements()
nextElement()
hasNext()
Next()
Remove()
hasNext();
next();
remove();
previous();
hasPrevious();
add()
set()
previousIndex();
nextIndex();

Sorting Interfaces

Comparable

  • Comparable interface is used for natural sorting order
  • Comparable is used in TreeSet and TreeMap

Comparator

  • Comparator interface is used for custom sorting order
  • Comparator is used in TreeSet and TreeMap

Utility Classes

Arrays

  • Arrays is utility class
  • It has methods to perform some utility operations like sorting, searching, min, max, sum etc. on arrays

Collections

  • Collections is utility class
  • It has methods to perform some utility operations like sorting, searching, min, max, sum etc. on collection objects

What is the difference between Collection and Collections?

Collection is an interface which can be used for representing a group of individual objects as a single entity. But Collections is a utility class defined several utility(sorting, searching, sum, max, min …etc.) methods.

Scroll to Top