--> Java Collection Framework In Simple Words » The Problem Solution

Java Collection Framework in Simple Words

When a group of individual objects acts as a single entity, known as a collection in Java. It provides an architecture to store and manipulate a group of objects. The Java Collection Framework (JCF) offers a wide range of data structures, each designed to handle different data types and operations efficiently.

Hierarchy of Collection Framework

collection hierarchy

List Interface:

  • Description: List is the direct child interface of the collection interface we would choose List where our requirements are like, duplicates are allowed, Insertion order should be maintained, and along null values are also allowed.
  • Common Implementations:
    • ArrayList: Implements a dynamic array that is growable in nature. Best suited for searching operations.
    • LinkedList: Implements a doubly linked list; useful for frequent insertions and deletions operations at any position of the list.
    • Vector: Similar to ArrayList but synchronized and thread-safe.
    • Stack: Extends Vector with additional methods for stack operations. Follows the FIFO(First-In-First-Out) rule.

Example:

import java.util.*;  

class TestListInterface{  
  	public static void main(String args[]) {
		    ArrayList<String> al = new ArrayList<String>();
		al.add("Biswa");
		al.add("Ranjan");
		al.add("Sahoo");
		al.add("Biswa");
		
		System.out.println("ArrayList: "+ al);
		
		LinkedList<Integer> ll = new LinkedList();
		ll.add(1);
		ll.add(2);
		ll.add(3);
		ll.add(1);
		
		System.out.println("LinkedList: "+ ll);
		
		Stack<String> st = new Stack<>();
		// here we can use both add and push insert operation
		st.add("Biswa");
		st.push("Ranjan");
		st.add("Sahoo");
		st.push("Biswa");

		System.out.println("Stack: "+ st);
		
		Vector<Integer> vc = new Vector<>();
		vc.add(10);
		vc.add(20);
		vc.add(30);
		vc.add(10);
		
		System.out.println("Vector: "+ vc);
	}
} 
The Problem Solution
Output
ArrayList: [Biswa, Ranjan, Sahoo, Biswa]
LinkedList: [1, 2, 3, 1]
Stack: [Biswa, Ranjan, Sahoo, Biswa]
Vector: [10, 20, 30, 10]

Set Interface:

  • Description: Set is also the direct child interface of the collection interface we would choose Set where our requirements are like, duplicates are not allowed, don’t care about the order, and more than one null values are not allowed.
  • Common Implementations:
    • HashSet: Implements a set using a hash table for storage, allowing fast retrieval.
    • LinkedHashSet: Maintains insertion order, allowing predictable iteration order.
    • SortedSet: maintains its elements in ascending order, sorted according to the elements’ natural ordering or according to a Comparator provided at SortedSet creation time.
    • NavigableSet: It functions similarly to a SortedSet but offers additional navigation methods alongside its sorting capabilities.
    • TreeSet: Implements a set stored in a tree structure, providing ordered iteration based on elements’ natural ordering or a custom Comparator. But here only homogeneous elements are allowed.

Example:

import java.util.*;

public class TestSetInterface{

	public static void main(String args[]) {
		HashSet<String> hc = new HashSet<String>();
		// I have added one duplicate here, but it will not accept the duplicates
		hc.add("Biswa");
		hc.add("Ranjan");
		hc.add("Sahoo");
		hc.add("Biswa");
		
		System.out.println("HashSet: "+ hc);
		
		LinkedHashSet<Integer> lhc = new LinkedHashSet();
		lhc.add(1);
		lhc.add(2);
		lhc.add(3);
		lhc.add(1);
		
		System.out.println("LinkedHashSet: "+ lhc);
		
		SortedSet<Integer> ss = new TreeSet<>();
		// I have added high to low, but it will print in ascending order
		ss.add(50);
		ss.add(40);
		ss.add(30);
		ss.add(20);
		ss.add(20);
		
		System.out.println("SortedSet: "+ ss);
		
		TreeSet<String> ts = new TreeSet<>();
		// TreeSet has the default order as ascending, check the output
		ts.add("Sahoo");
		ts.add("Biswa");
		ts.add("Ranjan");
		ts.add("Biswa");
		
		System.out.println("TreeSet: "+ ts);
	}
}
The Problem Solution
Output
HashSet: [Biswa, Sahoo, Ranjan]
LinkedHashSet: [1, 2, 3]
SortedSet: [10, 20, 30, 50]
TreeSet: [Biswa, Ranjan, Sahoo]

Queue Interface:

  • Description: It is designed for holding elements prior to processing. We can choose this interface when we need some flexibility in adding and removing elements from the collection and along with it follows the LIFO(Last In First Out) rule.
  • Common Implementations:
    • LinkedList: Implements both List and Queue interfaces, often used as a double-ended queue (Deque).
    • PriorityQueue: It functions similarly to a SortedSet but excels by enabling efficient insertion and removal operations based on element priority.
    • ArrayDeque: It allows for the addition or removal of elements from both ends. An ArrayDeque implementation can function as a Stack (Last-In-First-Out) or a Queue (First-In-First-Out).

Example:

import java.util.*;

public class TestQueueInterface {

	public static void main(String args[]) {
		PriorityQueue<String> pq = new PriorityQueue<String>();
		// we can use both add and offer for insert operation
		// check the output, it will print as per the priority basis
		pq.add("Biswa");
		pq.add("Ranjan");
		pq.offer("Sahoo");
		pq.offer("Biswa");
		
		System.out.println("PriorityQueue: "+ pq);
		
		ArrayDeque<Integer> ad = new ArrayDeque<>();
		// we can add both side of this collection
		ad.add(1);
		ad.add(2);
		ad.addFirst(4);
		ad.addLast(5);
		ad.add(3);
		
		System.out.println("ArrayDeque: "+ ad);
	}
}
The Problem Solution
Output
PriorityQueue: [Biswa, Biswa, Sahoo, Ranjan]
ArrayDeque: [4, 1, 2, 5, 3]

Map Interface:

  • Description: Map is a separate thing, It is not part of the collection interface but the part of the collection framework that holds both the key and value pair known as Entry. So when our requirement comes like processing the collection with key and value pair then we will blindly go for Map Interface.
  • Common Implementations:
    • HashTable: It achieves constant time complexity for insertion, deletion, and lookup operations.
    • HashMap: Implements a hash table for storing key-value pairs, allowing fast retrieval.
    • LinkedHashMap: Maintains insertion order, allowing predictable iteration order.
    • SortedMap: It maintains its entries in ascending order, sorted according to the keys’ natural ordering, or based on a Comparator provided during the creation of the SortedMap.
    • TreeMap: Implements a map stored in a tree structure, providing ordered iteration based on keys’ natural ordering or a custom Comparator. It allows only homogeneous elements.

Example:


import java.util.*;

public class CharracterCount {

	public static void main(String args[]) {
		HashMap<Integer, String> hm = new HashMap<>();  
		hm.put(1, "Biswa");
		hm.put(2, "Ranjan");
		hm.put(3, "Sahoo");
		hm.put(1, "Biswa");
		
		System.out.println("HashMap: "+ hm);
		
		LinkedHashMap<Integer, String> lhm = new LinkedHashMap<>();  
		lhm.put(1, "Biswa");
		lhm.put(2, "Ranjan");
		lhm.put(3, "Sahoo");
		lhm.put(1, "Biswa");
		
		System.out.println("LinkedHashMap: "+ lhm);
		
		SortedMap<Integer, String> sm = new TreeMap<>();  
		sm.put(2, "Ranjan");
		sm.put(3, "Sahoo");
		sm.put(1, "Biswa");
		sm.put(1, "Biswa");
		
		System.out.println("SortedMap: "+ sm);
		
		TreeMap<Integer, String> tm = new TreeMap<>();  
		tm.put(2, "Ranjan");
		tm.put(3, "Sahoo");
		tm.put(1, "Biswa");
		tm.put(1, "Biswa");
		
		System.out.println("TreeMap: "+ tm);
		
		System.out.println("\nExtracting the key and values by using entryset,\n");
		tm.entrySet().forEach(f -> System.out.println(f.getKey()+" - "+f.getValue()));
	}
}
The Problem Solution
Output
HashMap: {1=Biswa, 2=Ranjan, 3=Sahoo}
LinkedHashMap: {1=Biswa, 2=Ranjan, 3=Sahoo}
SortedMap: {1=Biswa, 2=Ranjan, 3=Sahoo}
TreeMap: {1=Biswa, 2=Ranjan, 3=Sahoo}

Extracting the key and values by using entryset,

1 - Biswa
2 - Ranjan
3 - Sahoo

Why are collections called frameworks?

Collections are called frameworks because they provide a standard way to work with groups of objects in Java. This framework includes common interfaces, classes, and methods to store, access, and manage data. It simplifies tasks by offering ready-made tools and structures, so you don’t have to build them from scratch. This organized system makes coding easier and more efficient, ensuring that different parts of your program can work together smoothly.

What is a framework in Java?

A Java framework is a pre-written code set that helps developers build applications more easily. It includes reusable components, tools, and libraries that provide common functionality, so you don’t have to write everything from scratch. Frameworks offer a standard way to build and organize your code, making development faster and more efficient. They help handle repetitive tasks, allowing you to focus on the unique parts of your application. Examples include the Java Collections Framework, which provides structures like lists and sets, and Spring, which helps with building web applications.

What are the two parts of the Java collection framework?

The two parts of the Java Collection Framework are:

  1. Interfaces: These define the types of collections, such as List, Set, and Map. They specify what operations can be performed on a collection, like adding or removing elements.
  2. Implementations: These are the concrete classes that provide the actual functionality of the interfaces, like ArrayList, HashSet, and HashMap. They define how the collections work and store the data.

Together, interfaces and implementations make it easy to work with different types of data collections consistently.

What is the difference between ArrayList and collection?

An ArrayList is a specific type of collection in Java. A collection is a general term for a group of objects, managed together, and includes various types like lists, sets, and maps. An ArrayList, specifically, is a resizable array that allows you to add and remove elements dynamically. It is part of the Java Collection Framework and implements the List interface, providing ordered and indexed access to elements. In contrast, a collection could be any data structure that holds multiple elements, such as a HashSet or a TreeMap, not just an ArrayList.

Leave a Reply

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