Collection Framework in Java – A Detailed Overview

Updated on August 22, 2024

Article Outline

A collection, often known as a container, is just an item that combines several different items into one unit. Aggregate data is stored, retrieved, altered, and shared via collections and can be imported further in a different class to use. They usually depict data elements that naturally form a group, like a phone directory or a mail folder that contains a collection of messages. There is a collections structure built into the Java platform.

 

An object (like the traditional Vector class) that represents a collection of objects is called a collection. A collections framework allows collections to be handled without regard to implementation details by providing a consistent architecture for representing and working with collections.

 

In this article, we will learn about the Collection Framework in Java. We will cover various components in this article including the hierarchy of the collection framework in Java, methods used by the collection interface, various interfaces such as Set, List, Map, Queue, etc., along with each of their detailed examples of code with their output.

What is the Java Collection Framework?

A collection of classes and interfaces that offer an already-built architecture is called a framework. There is no requirement to define a framework to implement a new feature or class. A unified architecture for representing and working with collections is known as a collections framework. With the Java Collection Framework, the user can store, search, sort, insert, remove, and update data on a set of elements, among other data manipulation functions. The following are present in every collection framework:

 

  • Interfaces: These are collections representing abstract data types. Collections can be manipulated without regard to the specifics of their representation using interfaces. The interfaces form a hierarchy in Java.

 

  • Implementations: These are the reusable data structures that are implemented by the interfaces.

 

  • Algorithms: These are efficient methods that work with objects that implement collection interfaces to carry out practical calculations like sorting and searching as reusable implementations.
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Hierarchy of Java Collection Framework

The java.util package contains the Java Collection Framework. The fundamental Java classes and interfaces for collections are provided by the java.util package. An iterable interface is present in the collection framework which allows an iterator to iterate over every collection. The primary collection interface, which serves as the collection framework’s root, extends this interface. By extending this collection interface, all collections also expand the iterator’s attributes and this interface’s methods.

Java Collection Interfaces are divided into two types:

 

  • Collection interface (java.util.Collection)- It includes java.util.Set, java.util.SortedSet, java.util.NavigableSet, java.util.Queue, java.util.concurrent.BlockingQueue, java.util.concurrent.TransferQueue, java.util.Deque, and java.util.concurrent.BlockingDeque.
  • Map interface (java.util.Map)- It includes java.util.SortedMap, java.util.NavigableMap, java.util.concurrent.ConcurrentMap, java.util.concurrent.ConcurrentNavigableMap.

Methods of the Collection Interface

The fundamental methods that all collection classes need to implement are specified by the collection interface. All collections that implement this interface can directly use the different methods contained in this interface. Common methods of the collection interface are as follows:

 

  • add(): This optional operation adds the given element to the collection.
  • remove(Object objName): If the provided element is present, this optional operation eliminates one instance of it from the collection.
  • containsAll(): This function determines whether the collection includes every element in the given collection.
  • addAll(): This optional method adds every element from the given collection to this collection.
  • size(): It gives back the collection’s total number of elements.
  • isEmpty(): It determines whether the collection is empty.
  • contains(Object objName): It determines whether the given element is present in the collection.
  • iterator(): It provides an iterator across the collection’s elements.
  • clear(): This function takes away every element in this collection.
  • toArray(): It turns a collection into an array.
  • toArray(Type[] name): It transforms a collection into an array of a given type.
  • removeAll(): This optional action eliminates every element in the collection that is also a part of the given collection.
  • retainAll(): This optional procedure only keeps the collection’s elements that are part of the designated collection.
  • equals(Object objName): It checks for equality by comparing the given object to the collection.
  • hashCode(): It provides the collection’s hash code value.
  • stream(): It uses the collection as its source to return a sequential Stream.
  • parallelStream(): It provides the collection as the source of a potentially parallel stream.

Interfaces that Extends Core Collections in Java

Every general-purpose implementation of the Java platform supports every optional operation. A distinct type of data is stored on each of the several interfaces in the collection framework. Below is the list describing the core collection interfaces in Java:

Collection

A Collection in the Java Collections framework represents a group of objects known as its elements. The elements of a collection are a set of related objects. When the greatest degree of generality is required, collections are passed around and altered via the Collection interface. The collection interface does not implement any specific classes, but it acts as a foundational interface to provide methods and subclasses in Java. While duplicate components are permitted in some collections, they are not in others.

Set

An unordered group of items whose duplicate values cannot be kept is called a set. It is a collection in which duplicate components are not added. This interface is used to represent sets, such as the courses in a student’s syllabus, or the processes operating on a computer. It replicates the mathematical set abstraction. The set interface is implemented with the help of classes such as HashSet, TreeSet, LinkedHashSet, etc.

 

The classes implementing the List Interface in the Java Collections Framework are:

 

  • HashSet-

HashSet is a class implementation of the Set interface that keeps its elements in a hash table, but it doesn’t guarantee the sequence in which iterations will occur. The hashcodes of the objects are used to insert them. Additionally, NULL elements can be inserted using this class.

 

Example:

import java.util.HashSet; class HashSetExample { public static void main(String[] args) { // Create a HashSet of String type HashSet<String> set = new HashSet<>(); // Adding the data to the HashSet set.add("One"); set.add("Two"); set.add("Three"); set.add("Four"); // Printing the HashSet elements System.out.println("Elements in the HashSet are: "); for (String element : set) { System.out.println(element); } // Adding more data to the HashSet set.add("Five"); set.add("Six"); set.add("Seven"); set.add("Eight"); // Printing the HashSet elements after more data addition System.out.println("Elements in the HashSet are: "); for (String element : set) { System.out.println(element); } } }

Output:

Elements in the HashSet are: One Four Two Three Elements in the HashSet are: Eight Five Six One Four Seven Two Three
  • TreeSet-

TreeSet is a class implementation of the Set interface that is significantly slower than HashSet and arranges its elements according to their values while storing them in a tree known as a red-black tree.

 

Example:

import java.util.TreeSet; class TreeSetExample { public static void main(String[] args) { // Create a TreeSet of String type TreeSet<String> set = new TreeSet<>(); // Adding the data to the TreeSet set.add("One"); set.add("Two"); set.add("Three"); set.add("Four"); set.add("Five"); // Printing the TreeSet elements System.out.println("Elements in the TreeSet are: "); for (String element : set) { System.out.println(element); } } }

Output:

Elements in the TreeSet are: Five Four One Three Two
  • LinkedHashSet-

LinkedHashSet is a class implementation of the Set interface that is implemented as a linked list traversing a hash table. The elements of the list are arranged according to the order in which they were added to the set known as insertion order. The LinkedHashSet uses a doubly linked list to store the data so that the order of the elements can be retained.

 

Example:

import java.util.LinkedHashSet; class LinkedHashSetExample { public static void main(String[] args) { // Create a LinkedHashSet of String type LinkedHashSet<String> list = new LinkedHashSet<>(); // Adding the data to the LinkedHashSet list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); // Printing the LinkedHashSet elements System.out.println("Elements in the LinkedHashSet are: "); for (String element : list) { System.out.println(element); } // Adding more data to the LinkedHashSet list.add("Five"); list.add("Six"); list.add("Seven"); list.add("Eight"); // Printing the LinkedHashSet elements after more data addition System.out.println("Elements in the LinkedHashSet are: "); for (String element : list) { System.out.println(element); } } }

Output:

Elements in the LinkedHashSet are: One Two Three Four Elements in the LinkedHashSet are: One Two Three Four Five Six Seven Eight

List

A list is an ordered collection that is also referred to as a sequence. Duplicate elements can be added to the list in Java. To use a List, we can create objects with various available classes including ArrayList, LinkedList, etc. In most cases, the user of a list can access entries by their integer index (position) and can decide exactly where each piece is inserted in the list. It is similar to the C++ vector. In a List interface, two list objects are said to be equal if they contain the same elements in the same order.

 

The classes implementing the List Interface in the Java Collections Framework are:

 

  • ArrayList-

ArrayList is a class implementation of the List interface that provides random access to the list elements. The ArrayList interface is implemented using a resizable array. carries out all list operations that are optional and accepts all elements, even null. ArrayList class implements the List interface and further provides various methods for adjusting the size of the array used internally to hold the list.

 

Example:

import java.util.ArrayList; class ArrayListExample { public static void main(String[] args) { // Create an ArrayList of String type ArrayList<String> list = new ArrayList<>(); // Adding the data to the ArrayList list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); // Printing the ArrayList elements System.out.println("Elements in the ArrayList are: "); for (String element : list) { System.out.println(element); } list.remove(3); // add the index (0-based) // Printing the ArrayList elements after removal System.out.println("Elements in the ArrayList are: "); for (String element : list) { System.out.println(element); } // Adding more data to the ArrayList list.add("Five"); list.add("Six"); list.add("Seven"); list.add("Eight"); // Printing the ArrayList elements after more data addition System.out.println("Elements in the ArrayList are: "); for (String element : list) { System.out.println(element); } } }

Output:

Elements in the ArrayList are: One Two Three Four Elements in the ArrayList are: One Two Three Elements in the ArrayList are: One Two Three Five Six Seven Eight
  • LinkedList-

LinkedList is a class implementation of the List interface using a linear data structure (doubly linked list) in which the components are not stored at contiguous locations. It allows all elements (including null) and performs all optional list operations like a doubly linked list. Any operations that index into the list will start at the beginning and work their way down to the end, depending on which is nearest to the given index.

 

Example:

import java.util.LinkedList; class LinkedListExample { public static void main(String[] args) { // Create a LinkedList of Integer type LinkedList<Integer> list = new LinkedList<>(); // Adding the int data to the linked list list.add(1010); list.add(1011); list.add(1012); list.add(1013); // Printing the linked list elements System.out.println("Elements in the Linked List are: "); for (Integer element : list) { System.out.println(element); } list.remove(3); // add the index (0-based) // Printing the linked list elements after removal System.out.println("Elements in the Linked List are: "); for (Integer element : list) { System.out.println(element); } } }

Output:

Elements in the Linked List are: 1010 1011 1012 1013 Elements in the Linked List are: 1010 1011 1012

Queue

A Queue is a collection used to hold items while they are being processed. Like an actual queue line, a queue interface preserves the First In First Out (FIFO) order. Queues provide various methods like insertion, removal, and inspection operations apart from the basic collection methods. When the element’s order matters, this interface is used to store every element.

 

The classes implementing the Queue Interface in the Java Collections Framework are:

 

  • PriorityQueue-

PriorityQueue is a class implementation of the Queue interface that is used when objects are processed based on priority. Depending on whether the constructor is used, the elements of the priority queue are sorted either by a Comparator provided at the time of queue creation or by the natural ordering. Null elements are not allowed in a priority queue.

 

Example:

import java.util.PriorityQueue; class DeQueExample { public static void main(String[] args) { // Create a PriorityQueue of Integer type PriorityQueue<String> pq = new PriorityQueue<>(); // Adding the int data to the priority queue pq.add("four"); pq.add("three"); pq.add("second"); pq.add("first"); // Printing the priority queue elements System.out.println("Elements in the Priority queue are: "); while (!pq.isEmpty()) { System.out.println(pq.poll()); } } }

Output:

Elements in the Priority queue are: first four second three

Deque

A deque, also known as a double-ended queue, is a type of data structure in which elements can be added or removed from either end. It is a collection that is used to store several elements before processing. This class offers additional insertion, extraction, and inspection procedures in addition to basic collection activities.

 

The classes implementing the Deque Interface in the Java Collections Framework are:

 

  • ArrayDeque-

ArrayDeque is a class implementation of the Deque interface that uses a resizable array to store elements. This class provides efficient insertion and removal operations from both ends. In this class, the NULL elements are prohibited. When we use the ArrayDeque as a queue, it becomes faster than LinkedList and Stack.

 

Example:

import java.util.ArrayDeque; class DeQueExample { public static void main(String[] args) { // Create an ArrayDeque of Integer type ArrayDeque<Integer> dq = new ArrayDeque<>(); // Adding the int data to the Arraydeque dq.add(101); dq.add(102); dq.add(103); dq.add(104); // Printing the deque elements before operations System.out.println("Elements in the Deque: "); for (Integer el : dq) { System.out.println(el); } // Demonstrating deque operations dq.addFirst(100); dq.addLast(105); // Printing the deque elements after operations System.out.println("Deque after adding elements at first and last:"); for (Integer el : dq) { System.out.println(el); } } }

Output:

Elements in the Deque: 101 102 103 104 Deque after adding elements at first and last: 100 101 102 103 104 105

Map

A Map interface is a data structure that supports the key – value pair needed to map the data. A map is an object that associates or maps the values with keys. A key can map to a maximum of one value in a map; multiple keys are not allowed. If there is data and we want to do actions based on the key, then a map is useful. If you have already learned about HashSet, then learning map is easy as it uses the same concept also.

 

The classes implementing the Map Interface in the Java Collections Framework are:

 

  • HashMap-

HashMap is a class implementation of the Map interface that keeps its elements in a hash map, but it doesn’t guarantee the sequence in which iterations will occur. The HashMap provides constant-time performance for the insertion (put) and fetches (get) operations. HashMap stores the data as the (Key, Value) pairs. For accessing the value in a HashMap, a key is used. Additionally, NULL elements and NULL keys can be inserted using this class.

 

Example:

import java.util.HashMap; import java.util.Map; class HashMapExample { public static void main(String[] args) { // Create a HashMap of Int and String and Key and Value pair HashMap<Integer, String> map = new HashMap<>(); // Add the data as key and value to the map map.put(1, "Welcome to Java course!"); map.put(2, "Welcome to C++ course!"); map.put(3, "Welcome to JavaScript course!"); map.put(4, "Welcome to Python course!"); map.put(5, "Welcome to Go lang course!"); // Traverse the Map to get all values from Map for (Map.Entry<Integer, String> et : map.entrySet()) { System.out.println("The stored data in the HashMap at Key " + et.getKey() + ": " + et.getValue()); } // Getting a single value from the Map System.out.println("The stored value in the HashMap at 1: " + map.get(3)); } }

Output:

The stored data in the HashMap at Key 1: Welcome to Java course! The stored data in the HashMap at Key 2: Welcome to C++ course! The stored data in the HashMap at Key 3: Welcome to JavaScript course! The stored data in the HashMap at Key 4: Welcome to Python course! The stored data in the HashMap at Key 5: Welcome to Go lang course! The stored value in the HashMap at 1 Welcome to JavaScript course!
  • TreeMap-

TreeMap is a class implementation of NavigableMap based on Red-Black trees. TreeMap allows us to store our data as a Key and Value pair but in a sorted order. Depending on which constructor is used, the map is sorted either by a Comparator supplied at map construction time or by the natural ordering of its keys. The class provides operations such as containsKey, get, put, and delete, and provides a guaranteed log(n) time costs with this implementation. The class can have more than one NULL value but cannot have a NULL key. The Java TreeMap lacks synchronisation.

 

Example:

import java.util.TreeMap; import java.util.Map; class HashMapExample { public static void main(String[] args) { // Create a HashMap of Int and String and Key and Value pair TreeMap<Integer, String> map = new TreeMap<>(); // Add the data as key and value to the map map.put(1, "Welcome to Java course!"); map.put(2, "Welcome to C++ course!"); map.put(3, "Welcome to JavaScript course!"); map.put(4, "Welcome to Python course!"); map.put(5, "Welcome to Go lang course!"); // Traverse the Map to get all values from Map for (Map.Entry<Integer, String> et : map.entrySet()) { System.out.println("The stored data in the TreeMap at Key " + et.getKey() + ": " + et.getValue()); } // Getting a single value from the Map System.out.println("The stored value in the TreeMap at 1: " + map.get(2)); } }

Output:

The stored data in the HashMap at Key 1: Welcome to Java course! The stored data in the HashMap at Key 2: Welcome to C++ course! The stored data in the HashMap at Key 3: Welcome to JavaScript course! The stored data in the HashMap at Key 4: Welcome to Python course! The stored data in the HashMap at Key 5: Welcome to Go lang course! The stored value in the HashMap at 1: Welcome to C++ course!
  • LinkedHashMap-

LinkedHashMap is a class implementation of the Map interface based on LinkedList and HashTable. In contrast to HashMap, this class keeps track of every entry in a doubly-linked list. The iteration order, which is often the order in which keys were placed into the map (insertion order), is defined by this linked list. Unique entries and values based on the key are contained in the LinkedHashMap. Apart from all of this, it can contain one NULL key and several NULL values. The LinkedHashMap lacks synchronisation.

 

Example:

import java.util.LinkedHashMap; import java.util.Map; class HashMapExample { public static void main(String[] args) { // Create a LinkedHashMap of Int and String and Key and Value pair LinkedHashMap<Integer, String> map = new LinkedHashMap<>(); // Add the data as key and value to the map map.put(1, "Welcome to Java language!"); map.put(2, "Welcome to C++ language!"); map.put(3, "Welcome to JavaScript language!"); map.put(4, "Welcome to Python language!"); map.put(5, "Welcome to Go lang language!"); // Traverse the Map to get all values from Map for (Map.Entry<Integer, String> et : map.entrySet()) { System.out.println("The stored value in the LinkedHashMap at Key " + et.getKey() + ": " + et.getValue()); } // Getting a single value from the Map System.out.println("The stored value in the LinkedHashMap at 1: " + map.get(2)); } }

Output:

The stored value in the LinkedHashMap at Key 1: Welcome to Java language! The stored value in the LinkedHashMap at Key 2: Welcome to C++ language! The stored value in the LinkedHashMap at Key 3: Welcome to JavaScript language! The stored value in the LinkedHashMap at Key 4: Welcome to Python language! The stored value in the LinkedHashMap at Key 5: Welcome to Go lang language! The stored value in the LinkedHashMap at 1: Welcome to C++ language!

Benefits of Java Collection Framework?

When using a Java Collection Framework, there are various advantages that we can get, and some of them are:

 

  • Reduced programming effort: The Collections Framework frees you to focus on the crucial components of your application rather than the intricate “plumbing” that keeps it running by offering helpful data structures and algorithms. The Java Collections Framework enables interoperability among unrelated APIs thereby, reducing the programming effort.

 

  • Boosts program quality and speed: High-performance, high-quality implementations of practical data structures and algorithms are provided by this Collections Framework. Because each interface has multiple interchangeable implementations, programs can be readily modified by changing the collection implementations.

 

  • Reduces learning effort: Less work is required to acquire and utilise new APIs because many of them automatically take collections as input and provide them as output. Each of these APIs used to have a little sub-API dedicated to working with its collections.

 

  • Software Reuse: By their very nature, new data structures that follow the accepted collection interfaces can be reused. The new algorithms that function on entities that implement these interfaces are subject to the same rules.

 

  • Consistent API: The classes like ArrayList, LinkedList, Vector, etc., that implement the fundamental interfaces of Collection, Set, List, and Map share a common set of methods.

Conclusion

Working with collections of objects is made easier with the help of the robust and adaptable Java Collection Framework. In this article, we have learned in detail about the Collection Framework in Java. We have seen various methods of the collection interface that provide the foundation to implement various classes in Java. Set, List, Queue, Deque, and Map are interfaces that implement various classes.

 

The programmers who use Java programming may produce more effective, reusable, and manageable code with the framework’s standardised set of interfaces and classes. Any Java developer must be familiar with the main interfaces, classes, and algorithms in the Collection Framework to select the appropriate data structures and methods for the use cases that best suit their needs.

FAQs
The Collection Framework in Java is a unified architecture that is used to represent and handle collections of objects easily. It comprises a range of interfaces and classes that allow standardised manipulation of data groups, regardless of whether they are lists, sets, queues, or maps. This framework reduces the complexity of programming tasks by providing built-in algorithms for sorting, searching, and modifying data structures. The methods used by this approach lead to better performance through effective ways of managing data.
Java has two concepts denoted by "Collection" and "Collections," which are distinct from each other. The Collection is an interface in the Java Collection Framework that specifies a collection of objects and the operations that can be performed on them. Collections on the other hand is a utility class located in the java.util package. It is composed wholly of static methods that either act upon collections or return collections.
Java Collections is more of a framework than a library. A library is merely a collection of reusable functions or classes, but a framework offers a standard approach to constructing applications with its own set of rules. It does this by providing an outline and pre-defined methods and classes. The Java Collection Framework thus consists of a well-versed group of interfaces, classes, and concrete classes - all along with algorithms for manipulating collections.
Two major components of the Java Collection Framework are: interfaces and implementations. The interfaces offer abstract data types that depict collections like List, Set, and Map and specify the actions possible on these collections. Implementations are known as classes that realise these interfaces. It includes classes such as ArrayList, HashSet, and HashMap, etc. These classes provide details regarding data structures supported by the implementation class while also specifying how each operation from the interface is realised.
Collections are used in Java to handle several related objects together. This is achieved effectively and efficiently, and it provides a way for the storage, retrieval, manipulation, and communication of aggregate data. Using collections in Java allows developers access to built-in methods that may include searching and sorting algorithms as well as easy iteration over data, eliminating manual code creation of these common tasks and thus saving time and costs.

Updated on August 22, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved