1. Collection Frameworks in Java 8.0
Collection Framework in Java 8
The Collection Framework in Java 8 is a unified architecture that provides a set of
interfaces and classes for storing, processing, and manipulating collections of objects. It
simplifies the handling of data structures like lists, sets, and maps while improving
performance and reusability. Categories of Collection Framework
Java Collection Framework is divided into the following categories:
1. List Interface (Ordered collection, allows duplicates)
o Classes: ArrayList, LinkedList, Vector, Stack
2. Set Interface (Unordered collection, no duplicates)
o Classes: HashSet, LinkedHashSet, TreeSet
3. Queue Interface (FIFO or priority-based ordering)
o Classes: PriorityQueue, ArrayDeque
4. Map Interface (Key-value pairs, unique keys)
o Classes: HashMap, LinkedHashMap, TreeMap, Hashtable
Available Classes and Interfaces in Collection Framework
Interfaces
Collection
List
Set
Queue, Deque
Map
SortedSet
SortedMap
Classes
1. ArrayList, LinkedList,
Vector, Stack
2. HashSet, LinkedHashSet,
TreeSet
3. PriorityQueue, ArrayDeque
4. HashMap, LinkedHashMap,
TreeMap, Hashtable
2. Collection Frameworks in Java 8.0
List Interface Example: ArrayList
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("John");
names.add("Emma");
names.add("Oliver");
System.out.println("ArrayList elements: " + names);
// Retrieving an element
System.out.println("First element: " + names.get(0));
// Removing an element
names.remove("Emma");
System.out.println("After removing Emma: " + names);
}
}
Explanation
Creates an ArrayList of String type.
Adds elements using add().
Retrieves an element using get().
Removes an element using remove().
Expected Output
ArrayList elements: [John, Emma, Oliver]
First element: John
After removing Emma: [John, Oliver]
Real-time Usage
Used in dynamic arrays where random access is required, such as storing a list of
student names in an application.
Set Interface Example: HashSet
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<Integer> numbers = new HashSet<>();
numbers.add(10);
3. Collection Frameworks in Java 8.0
numbers.add(20);
numbers.add(30);
numbers.add(10); // Duplicate will be ignored
System.out.println("HashSet elements: " + numbers);
}
}
Explanation
Creates a HashSet that stores unique integers.
Adds duplicate element 10, but it is ignored.
Expected Output
HashSet elements: [10, 20, 30]
Real-time Usage
Used in scenarios where duplicate values must be avoided, like storing unique
customer IDs.
Queue Interface Example: PriorityQueue
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30);
pq.add(10);
pq.add(20);
System.out.println("PriorityQueue elements: " + pq);
System.out.println("Poll (removes highest priority element):
" + pq.poll());
System.out.println("Updated PriorityQueue: " + pq);
}
}
Explanation
PriorityQueue sorts elements in natural order.
poll() removes the smallest element (highest priority).
Expected Output
PriorityQueue elements: [10, 30, 20]
Poll (removes highest priority element): 10
4. Collection Frameworks in Java 8.0
Updated PriorityQueue: [20, 30]
Real-time Usage
Used in task scheduling (e.g., CPU process scheduling).
Map Interface Example: HashMap
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> empMap = new HashMap<>();
empMap.put(101, "John");
empMap.put(102, "Emma");
empMap.put(103, "Oliver");
System.out.println("HashMap: " + empMap);
System.out.println("Value for key 102: " + empMap.get(102));
empMap.remove(101);
System.out.println("After removing key 101: " + empMap);
}
}
Explanation
HashMap stores key-value pairs.
put() adds entries, get() retrieves values, and remove() deletes an entry.
Expected Output
HashMap: {101=John, 102=Emma, 103=Oliver}
Value for key 102: Emma
After removing key 101: {102=Emma, 103=Oliver}
Real-time Usage
Used in applications like maintaining employee records in an HR system.
Conclusion
Java 8 Collection Framework provides powerful data structures to handle and manipulate
data efficiently. Each class serves a unique purpose in real-world scenarios, such as:
ArrayList for dynamic lists.
HashSet for unique elements.
PriorityQueue for task scheduling.
HashMap for key-value storage.
5. Collection Frameworks in Java 8.0
Vector Class in Java Collection Framework
The Vector class in Java is a part of the java.util package and implements the List
interface. It is similar to an ArrayList but is synchronized, making it thread-safe. This
makes it a good choice for multi-threaded applications where multiple threads might access
the same collection.
Key Features of Vector
Dynamic Array: Grows dynamically as elements are added.
Thread-Safety: Methods like add(), remove(), and get() are synchronized.
Allows Duplicates: Unlike Set, Vector allows duplicate elements.
Random Access: Supports fast retrieval of elements using an index.
Enumeration & Iterator Support: It supports both Iterator and Enumeration to traverse
elements.
Real-Time Use Case: Managing an Online Course Student List
Let’s consider a scenario where an online course needs to store a list of students enrolled in
a course. Since multiple threads (like admin and students) might access or modify this list, a
synchronized list (Vector) ensures thread safety.
Java Program: Implementing Vector Class
import java.util.Vector;
import java.util.Iterator;
public class VectorExample {
public static void main(String[] args) {
// Creating a Vector to store student names
Vector<String> studentList = new Vector<>();
// Adding elements to the Vector
studentList.add("John");
studentList.add("Emma");
studentList.add("Michael");
studentList.add("Sarah");
// Displaying the Vector
System.out.println("Student List: " + studentList);
// Adding a new student at index 2
studentList.add(2, "David");
System.out.println("After adding 'David' at index 2: " +
studentList);
// Removing a student
studentList.remove("Emma");
System.out.println("After removing 'Emma': " + studentList);
6. Collection Frameworks in Java 8.0
// Retrieving an element
System.out.println("Student at index 1: " +
studentList.get(1));
// Iterating through the Vector using an Iterator
System.out.println("Iterating through the student list:");
Iterator<String> itr = studentList.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
// Checking if a student exists in the Vector
System.out.println("Is 'John' in the list? " +
studentList.contains("John"));
}
}
Explanation of Code
1. Creating a Vector<String>:
o Vector<String> studentList = new Vector<>(); creates a Vector to store
student names.
2. Adding Elements:
o add("John"), add("Emma"), etc., add students to the list.
o add(2, "David") adds a student at a specific position.
3. Removing Elements:
o remove("Emma") removes "Emma" from the list.
4. Retrieving Elements:
o get(1) retrieves the student at index 1.
5. Iterating Through the Vector:
o Uses an Iterator to print all elements.
6. Checking for an Element:
o contains("John") checks if "John" is in the list.
Expected Output
Student List: [John, Emma, Michael, Sarah]
After adding 'David' at index 2: [John, Emma, David, Michael,
Sarah]
After removing 'Emma': [John, David, Michael, Sarah]
Student at index 1: David
Iterating through the student list:
John
David
Michael
Sarah
Is 'John' in the list? true
7. Collection Frameworks in Java 8.0
Real-Time Use Case
Scenario: Managing an Online Course Enrollment System
The admin panel can add or remove students.
A Vector ensures thread safety when multiple users (admin and students) access the list.
Fast retrieval of students based on their enrollment order.
Duplicate student names allowed but can be controlled using contains().
Conclusion
The Vector class is useful for applications where: ✅ Thread safety is required.
Frequent modifications (adding/removing elements) occur.
Random access to elements is needed.
Hashtable Class in Java Collection Framework
The Hashtable class in Java is a part of the java.util package and implements the Map
interface. It is used to store key-value pairs, similar to HashMap, but with one key
difference—it is synchronized, meaning it is thread-safe.
Key Features of Hashtable
Stores Key-Value Pairs: Each key in a Hashtable is unique and maps to a specific value.
Thread-Safe: All methods are synchronized, making it suitable for multi-threaded
environments.
Does Not Allow Null Keys or Values: Unlike HashMap, Hashtable does not permit null keys
or null values.
Maintains No Order: Elements are stored based on their hash codes, and the order may not
be predictable.
Performance: Slightly slower than HashMap due to synchronization.
Real-Time Use Case: Employee Directory in a Company
A company wants to store employee details (ID and Name) in a system that multiple users
(HR, Manager, Employees) access simultaneously. Since multiple users might read or
update this data, a thread-safe collection like Hashtable is the best choice.
Java Program: Implementing Hashtable
import java.util.Hashtable;
import java.util.Enumeration;
public class HashtableExample {
public static void main(String[] args) {
// Creating a Hashtable to store Employee ID and Name
Hashtable<Integer, String> employeeTable = new
Hashtable<>();
8. Collection Frameworks in Java 8.0
// Adding elements to the Hashtable
employeeTable.put(101, "John");
employeeTable.put(102, "Emma");
employeeTable.put(103, "Oliver");
employeeTable.put(104, "Sophia");
// Displaying the Hashtable
System.out.println("Employee Directory: " + employeeTable);
// Retrieving a value using a key
System.out.println("Employee with ID 102: " +
employeeTable.get(102));
// Checking if a key exists
System.out.println("Is Employee ID 105 present? " +
employeeTable.containsKey(105));
// Checking if a value exists
System.out.println("Is 'Sophia' in the directory? " +
employeeTable.containsValue("Sophia"));
// Removing an entry from the Hashtable
employeeTable.remove(103);
System.out.println("After removing Employee ID 103: " +
employeeTable);
// Iterating through the Hashtable using Enumeration
System.out.println("Iterating through Employee Directory:");
Enumeration<Integer> keys = employeeTable.keys();
while (keys.hasMoreElements()) {
Integer key = keys.nextElement();
System.out.println("ID: " + key + ", Name: " +
employeeTable.get(key));
}
}
}
Explanation of Code
1. Creating a Hashtable<Integer, String>:
o Hashtable<Integer, String> employeeTable = new Hashtable<>();
creates a Hashtable to store Employee ID (Integer) as the key and Employee Name
(String) as the value.
2. Adding Elements:
o put(101, "John"), etc., stores employee details.
3. Retrieving an Element:
o get(102) retrieves the name of employee with ID 102.
4. Checking for a Key or Value:
o containsKey(105) checks if employee ID 105 exists.
9. Collection Frameworks in Java 8.0
o containsValue("Sophia") checks if "Sophia" exists in the list.
5. Removing an Entry:
o remove(103) deletes the entry for Employee ID 103.
6. Iterating Through the Hashtable:
o Uses Enumeration to loop through all elements.
Expected Output
Employee Directory: {101=John, 102=Emma, 103=Oliver,
104=Sophia}
Employee with ID 102: Emma
Is Employee ID 105 present? false
Is 'Sophia' in the directory? true
After removing Employee ID 103: {101=John, 102=Emma,
104=Sophia}
Iterating through Employee Directory:
ID: 101, Name: John
ID: 102, Name: Emma
ID: 104, Name: Sophia
Real-Time Use Case
Scenario: Employee Directory in a Multi-User HR System
HR Department, Managers, and Employees need access to employee data.
A Hashtable ensures thread safety when multiple users simultaneously access or modify
the employee database.
Fast lookups allow retrieving employee details quickly.
No null values prevent accidental missing data.
Comparison: Hashtable vs. HashMap
Feature Hashtable HashMap
Thread Safety Yes (synchronized) No (not synchronized)
Null Keys/Values Not Allowed Allowed
Performance Slower due to synchronization Faster
Use Case Multi-threaded applications General-purpose collections
Conclusion
The Hashtable class is an excellent choice when:
Thread safety is required.
Fast lookup operations (key-value pairs) are needed.
Null keys/values should be avoided (e.g., Employee ID system).
LinkedList Class in Java Collection Framework
The LinkedList class in Java is part of the java.util package and implements the List and
Deque interfaces. It is a doubly linked list that allows fast insertions and deletions compared
to ArrayList, making it a great choice for applications requiring frequent modifications.
10. Collection Frameworks in Java 8.0
Key Features of LinkedList
Doubly Linked List Implementation: Each node has references to both its previous and next
nodes.
Efficient Insertions/Deletions: Faster than ArrayList for adding/removing elements in the
middle.
Allows Duplicates & Null Elements: Unlike Set, it allows duplicate elements.
Can Be Used as a List, Queue, or Deque: Implements List, Queue, and Deque interfaces.
Maintains Insertion Order: Elements are stored in the order they were added.
Real-Time Use Case: Train Ticket Reservation System
A train ticket reservation system needs to maintain a waiting list of passengers. Since
passengers might cancel their bookings, removing an element from the middle of the list
should be fast. LinkedList is ideal for this scenario because of its efficient insertion and
deletion operations.
Java Program: Implementing LinkedList
import java.util.LinkedList;
import java.util.Iterator;
public class LinkedListExample {
public static void main(String[] args) {
// Creating a LinkedList to store passenger names
LinkedList<String> waitingList = new LinkedList<>();
// Adding elements to the LinkedList
waitingList.add("Alice");
waitingList.add("Bob");
waitingList.add("Charlie");
waitingList.add("David");
// Displaying the LinkedList
System.out.println("Initial Waiting List: " + waitingList);
// Adding a passenger at the beginning
waitingList.addFirst("Zara");
System.out.println("After adding 'Zara' at the beginning: "
+ waitingList);
// Adding a passenger at the end
waitingList.addLast("Ethan");
System.out.println("After adding 'Ethan' at the end: " +
waitingList);
// Removing a passenger from the middle
waitingList.remove("Charlie");
11. Collection Frameworks in Java 8.0
System.out.println("After removing 'Charlie': " +
waitingList);
// Checking the first and last passenger
System.out.println("First passenger in waiting list: " +
waitingList.getFirst());
System.out.println("Last passenger in waiting list: " +
waitingList.getLast());
// Iterating through the LinkedList using an Iterator
System.out.println("Iterating through the waiting list:");
Iterator<String> itr = waitingList.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
// Checking if a passenger is on the list
System.out.println("Is 'Alice' on the waiting list? " +
waitingList.contains("Alice"));
}
}
Explanation of Code
1. Creating a LinkedList<String>:
o LinkedList<String> waitingList = new LinkedList<>(); creates a list
for passenger names.
2. Adding Elements:
o add("Alice"), add("Bob"), etc., add passengers to the waiting list.
o addFirst("Zara") adds a passenger at the beginning.
o addLast("Ethan") adds a passenger at the end.
3. Removing Elements:
o remove("Charlie") removes a specific passenger.
4. Retrieving First and Last Elements:
o getFirst() retrieves the first passenger.
o getLast() retrieves the last passenger.
5. Iterating Through the LinkedList:
o Uses an Iterator to print all elements.
6. Checking for a Passenger:
o contains("Alice") checks if "Alice" is on the list.
Expected Output
Initial Waiting List: [Alice, Bob, Charlie, David]
After adding 'Zara' at the beginning: [Zara, Alice, Bob,
Charlie, David]
After adding 'Ethan' at the end: [Zara, Alice, Bob, Charlie,
David, Ethan]
After removing 'Charlie': [Zara, Alice, Bob, David, Ethan]
12. Collection Frameworks in Java 8.0
First passenger in waiting list: Zara
Last passenger in waiting list: Ethan
Iterating through the waiting list:
Zara
Alice
Bob
David
Ethan
Is 'Alice' on the waiting list? true
Real-Time Use Case
Scenario: Train Ticket Reservation System
A LinkedList is used to maintain a waiting list of passengers.
If a passenger cancels, removing them from the list is efficient.
New passengers can be added at the beginning or end as required.
Maintaining order is important for FIFO (First-In-First-Out) processing.
Comparison: LinkedList vs. ArrayList
Feature LinkedList ArrayList
Implementation Doubly Linked List Dynamic Array
Insertion/Deletion Faster (O(1) at start/middle) Slower (O(n) for middle)
Random Access Slower (O(n)) Faster (O(1))
Memory Usage Higher (extra node references) Lower
Best Use Case Frequent insertions/removals Frequent random access
The LinkedList class is best when:
Frequent insertions and deletions are needed.
FIFO (First-In-First-Out) processing is required.
Order must be maintained, such as in waiting lists, history logs, and undo
operations.
SortedSet Interface in Java
The SortedSet interface in Java is part of the java.util package and extends the Set
interface. It provides a way to store unique elements in a sorted order.
Key Features of SortedSet
No Duplicates: Like Set, it does not allow duplicate elements.
Sorted Order: Elements are sorted in natural order (ascending for numbers, alphabetical
for strings).
Implements NavigableSet: The main implementation of SortedSet is TreeSet, which also
implements NavigableSet.
Retrieval Methods:
o first() – Returns the first (lowest) element.
13. Collection Frameworks in Java 8.0
o last() – Returns the last (highest) element.
o headSet(E element) – Returns elements before the given element.
o tailSet(E element) – Returns elements after or equal to the given element.
o subSet(E fromElement, E toElement) – Returns a range of elements.
Real-Time Use Case: Student Roll Numbers in a School
A school wants to store student roll numbers in sorted order and ensure there are no
duplicates. SortedSet is the best choice because:
The roll numbers are stored in ascending order automatically.
Duplicate roll numbers are not allowed.
The first and last roll numbers can be retrieved easily.
Java Program: Implementing SortedSet Using TreeSet
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetExample {
public static void main(String[] args) {
// Creating a SortedSet (TreeSet) to store student
roll numbers
SortedSet<Integer> rollNumbers = new TreeSet<>();
// Adding roll numbers to the SortedSet
rollNumbers.add(105);
rollNumbers.add(101);
rollNumbers.add(108);
rollNumbers.add(103);
rollNumbers.add(102);
// Displaying the SortedSet
System.out.println("Sorted Roll Numbers: " +
rollNumbers);
// Getting the first and last elements
System.out.println("First Roll Number: " +
rollNumbers.first());
System.out.println("Last Roll Number: " +
rollNumbers.last());
// Getting elements before a specific roll number
System.out.println("Roll numbers before 105: " +
rollNumbers.headSet(105));
// Getting elements from a specific roll number
onwards
System.out.println("Roll numbers from 103 onwards: " +
rollNumbers.tailSet(103));
14. Collection Frameworks in Java 8.0
// Getting a range of roll numbers
System.out.println("Roll numbers between 102 and 108:
" + rollNumbers.subSet(102, 108));
// Trying to add a duplicate roll number (ignored)
rollNumbers.add(101);
System.out.println("After adding duplicate 101: " +
rollNumbers);
}
}
Explanation of Code
1. Creating a SortedSet<Integer>:
o SortedSet<Integer> rollNumbers = new TreeSet<>(); creates a sorted
set for storing roll numbers.
2. Adding Elements:
o add(105), add(101), etc., adds roll numbers (in an unsorted manner).
3. Automatic Sorting:
o TreeSet automatically sorts roll numbers in ascending order.
4. Retrieving First and Last Elements:
o first() returns the smallest roll number.
o last() returns the largest roll number.
5. Retrieving Subsets of Elements:
o headSet(105) returns roll numbers less than 105.
o tailSet(103) returns roll numbers from 103 onwards.
o subSet(102, 108) returns roll numbers from 102 (inclusive) to 108 (exclusive).
6. Duplicate Handling:
o add(101) attempts to add a duplicate roll number, but SortedSet ignores it.
Expected Output
Sorted Roll Numbers: [101, 102, 103, 105, 108]
First Roll Number: 101
Last Roll Number: 108
Roll numbers before 105: [101, 102, 103]
Roll numbers from 103 onwards: [103, 105, 108]
Roll numbers between 102 and 108: [102, 103, 105]
After adding duplicate 101: [101, 102, 103, 105, 108]
Real-Time Use Case
Scenario: Student Roll Number Management
A school database needs to maintain a sorted list of student roll numbers.
Ensures unique roll numbers (no duplicates).
Automatically sorts roll numbers when a new student is added.
Fast retrieval of roll numbers within a range (e.g., students in a specific class).
15. Collection Frameworks in Java 8.0
Comparison: SortedSet vs. HashSet vs. TreeSet
Feature SortedSet (TreeSet) HashSet LinkedHashSet
Order Sorted (Natural Order) Unordered Insertion Order
Duplicates Not Allowed Not Allowed Not Allowed
Performance Slower (O(log n)) Fast (O(1)) Moderate (O(1))
Use Case Sorted, Unique Data Unique, Fast Lookup Ordered Unique Data
Conclusion
The SortedSet (implemented as TreeSet) is best when:
Data must be sorted automatically (e.g., Student Roll Numbers).
Duplicate values should not be allowed.
Efficient range queries (subSet, headSet, tailSet) are required.
Stack Class in Java Collection Framework
The Stack class in Java is a Last In, First Out (LIFO) data structure. It extends Vector,
meaning it has all the properties of a dynamic array while providing additional stack-specific
methods.
Key Features of Stack
Follows LIFO (Last In, First Out): The last element added is the first to be removed.
Implements push() and pop() Methods:
o push(E item): Adds an item to the top of the stack.
o pop(): Removes and returns the top item from the stack.
o peek(): Returns the top element without removing it.
o isEmpty(): Checks if the stack is empty.
o search(E item): Returns the 1-based position of an element in the stack.
Real-Time Use Case: Web Browser Back Button
A web browser uses a stack to keep track of visited web pages.
When the user visits a new webpage, it is pushed onto the stack.
When the user clicks the Back button, the most recent page is popped from the stack, taking
the user to the previous page.
Java Program: Implementing Stack in a Web Browser Back Navigation
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
16. Collection Frameworks in Java 8.0
// Creating a Stack to store browser history
Stack<String> browserHistory = new Stack<>();
// Pushing webpages onto the stack
browserHistory.push("Google.com");
browserHistory.push("Facebook.com");
browserHistory.push("YouTube.com");
browserHistory.push("StackOverflow.com");
// Displaying the Stack
System.out.println("Current Browser History: " +
browserHistory);
// Getting the current page (Top of the Stack)
System.out.println("Current Page: " +
browserHistory.peek());
// Going Back (Popping the top page)
System.out.println("Going Back from: " +
browserHistory.pop());
System.out.println("Now on Page: " +
browserHistory.peek());
// Checking if Stack is empty
System.out.println("Is browser history empty? " +
browserHistory.isEmpty());
// Searching for a website in history
System.out.println("Position of 'Google.com' in
history: " + browserHistory.search("Google.com"));
}
}
Explanation of Code
1. Creating a Stack<String>:
o Stack<String> browserHistory = new Stack<>(); creates a stack to store
webpage URLs.
2. Adding Web Pages (Pushing to Stack):
o push("Google.com"), push("Facebook.com"), etc., add pages to the history
stack.
3. Checking the Current Page (peek()):
o peek() returns the last visited page (top of the stack).
4. Going Back (pop()):
o pop() removes the most recent page, simulating the Back button.
5. Checking Stack Status (isEmpty()):
o isEmpty() checks if there are any more pages left in history.
6. Searching for a Page (search()):
17. Collection Frameworks in Java 8.0
o search("Google.com") finds the position of Google.com in the history stack.
Expected Output
Current Browser History: [Google.com, Facebook.com,
YouTube.com, StackOverflow.com]
Current Page: StackOverflow.com
Going Back from: StackOverflow.com
Now on Page: YouTube.com
Is browser history empty? false
Position of 'Google.com' in history: 3
Real-Time Use Case
Scenario: Undo Feature in Text Editors
A stack is used in text editors to implement Undo functionality:
Every change made to a document is pushed onto the stack.
When the user presses Ctrl + Z, the last change is popped from the stack, restoring
the previous state.
Comparison: Stack vs. Queue vs. Deque
Feature Stack (LIFO) Queue (FIFO) Deque (Both Ends)
Insertion push() (Top) offer() (End) offerFirst() / offerLast()
Deletion pop() (Top) poll() (Front) pollFirst() / pollLast()
Access
Order
Last In, First Out
(LIFO)
First In, First Out
(FIFO)
Both Ends
Use Case Undo, Browser
History
Task Scheduling Double-ended
processing
Conclusion
The Stack class is best when:
Data must be processed in LIFO order (e.g., Browser History, Undo feature).
Pushing and popping elements is frequent.
Search and retrieval of the top element are needed.
Queue Interface in Java Collection Framework
The Queue interface in Java is part of the java.util package and follows the First In, First
Out (FIFO) principle. It is used to store elements sequentially, where the element added first
is processed first.
18. Collection Frameworks in Java 8.0
Key Features of Queue
FIFO (First In, First Out): The first element inserted is the first to be removed.
Different Implementations:
o LinkedList (Doubly Linked List-based Queue)
o PriorityQueue (Sorted Order Queue)
o ArrayDeque (Efficient Double-ended Queue)
Queue Methods:
o offer(E e): Adds an element to the queue.
o poll(): Removes and returns the head (first) element.
o peek(): Returns the head element without removing it.
o isEmpty(): Checks if the queue is empty.
Real-Time Use Case: Customer Service Ticket System
A customer support center uses a queue to handle service requests.
New customer requests are added to the queue.
Requests are processed in order (First Come, First Served).
When an agent is available, the first request is handled.
Java Program: Implementing Queue in a Customer Service System
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
// Creating a Queue to store customer service requests
Queue<String> customerQueue = new LinkedList<>();
// Adding customer requests (enqueue)
customerQueue.offer("Customer 1 - Billing Issue");
customerQueue.offer("Customer 2 - Technical Support");
customerQueue.offer("Customer 3 - Account Upgrade");
// Displaying the Queue
System.out.println("Customer Queue: " + customerQueue);
// Processing customers (dequeue)
System.out.println("Processing: " + customerQueue.poll());
// Removes Customer 1
System.out.println("Next in Queue: " +
customerQueue.peek()); // Shows Customer 2
// Processing another customer
System.out.println("Processing: " + customerQueue.poll());
// Removes Customer 2
19. Collection Frameworks in Java 8.0
// Checking if the queue is empty
System.out.println("Is the queue empty? " +
customerQueue.isEmpty());
// Displaying remaining queue
System.out.println("Remaining Queue: " + customerQueue);
}
}
Explanation of Code
1. Creating a Queue<String>:
o Queue<String> customerQueue = new LinkedList<>(); creates a queue
for customer service requests.
2. Adding Customers (offer()):
o offer("Customer 1 - Billing Issue") adds a customer request to the
queue.
3. Processing Customers (poll()):
o poll() removes the first request (head of the queue).
4. Checking the Next Customer (peek()):
o peek() retrieves the first element without removing it.
5. Checking Queue Status (isEmpty()):
o isEmpty() checks if any customers are waiting.
Expected Output:
Customer Queue: [Customer 1 - Billing Issue, Customer 2 - Technical
Support, Customer 3 - Account Upgrade]
Processing: Customer 1 - Billing Issue
Next in Queue: Customer 2 - Technical Support
Processing: Customer 2 - Technical Support
Is the queue empty? false
Remaining Queue: [Customer 3 - Account Upgrade]
Real-Time Use Case
Scenario: Task Scheduling in CPU
Operating systems use queues for task scheduling:
Processes waiting for CPU execution are stored in a queue.
The CPU executes the first process in the queue.
After execution, the next process is taken from the queue.
Comparison: Queue vs. Stack vs. Deque
Feature Queue (FIFO) Stack (LIFO) Deque (Both Ends)
Insertion offer() (End) push() (Top) offerFirst() /
offerLast()
Deletion poll() (Front) pop() (Top) pollFirst() /
pollLast()
20. Collection Frameworks in Java 8.0
Processing
Order
First In, First Out (FIFO) Last In, First Out
(LIFO)
Both Ends
Use Case Task Scheduling,
Customer Service
Undo, Browser
History
Double-ended
processing
Conclusion
The Queue interface is best when:
Data must be processed in FIFO order (e.g., Customer Service, Task Scheduling).
Efficient element retrieval from the front is required.
Handling requests in order is important.
Map Interface in Java Collection Framework
The Map interface in Java is part of the java.util package and is used to store key-value
pairs. Unlike List or Set, a Map does not allow duplicate keys.
Key Features of Map
Stores key-value pairs (key -> value).
Keys must be unique, but values can be duplicate.
Efficient searching, insertion, and deletion using keys.
Common Implementations:
o HashMap – Unordered, fast lookup.
o LinkedHashMap – Maintains insertion order.
o TreeMap – Sorted order (ascending by default).
Real-Time Use Case: Student Database System
A Map can be used to store student records where:
Student ID (Key) is unique.
Student Name (Value) stores the student’s name.
Java Program: Implementing Map in a Student Database
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// Creating a Map to store Student ID -> Student Name
Map<Integer, String> studentMap = new HashMap<>();
// Adding students (Key -> Value)
studentMap.put(101, "Alice");
studentMap.put(102, "Bob");
studentMap.put(103, "Charlie");
studentMap.put(104, "David");
21. Collection Frameworks in Java 8.0
// Displaying the Student Map
System.out.println("Student Records: " + studentMap);
// Fetching a student's name using their ID
System.out.println("Student with ID 102: " +
studentMap.get(102));
// Checking if a student ID exists
System.out.println("Is ID 105 present? " +
studentMap.containsKey(105));
// Removing a student record
studentMap.remove(103);
System.out.println("After removing student 103: " +
studentMap);
// Iterating through the Map
System.out.println("All Students:");
for (Map.Entry<Integer, String> entry :
studentMap.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: "
+ entry.getValue());
}
}
}
Explanation of Code
1. Creating a Map<Integer, String>:
o Map<Integer, String> studentMap = new HashMap<>(); creates a
HashMap to store student records.
2. Adding Entries (put()):
o put(101, "Alice") stores ID 101 -> Alice.
3. Fetching a Value (get()):
o get(102) returns the student name "Bob".
4. Checking Key Existence (containsKey()):
o containsKey(105) checks if ID 105 exists.
5. Removing an Entry (remove()):
o remove(103) removes Charlie’s record.
6. Iterating Through Map (entrySet()):
o for (Map.Entry<Integer, String> entry : studentMap.entrySet())
prints all ID -> Name pairs.
22. Collection Frameworks in Java 8.0
Expected Output
Student Records: {101=Alice, 102=Bob, 103=Charlie, 104=David}
Student with ID 102: Bob
Is ID 105 present? false
After removing student 103: {101=Alice, 102=Bob, 104=David}
All Students:
ID: 101, Name: Alice
ID: 102, Name: Bob
ID: 104, Name: David
Real-Time Use Cases
1. Employee Payroll System
Key → Employee ID
Value → Employee Salary
2. Caching in Web Applications
Key → URL
Value → Cached Page Data
3. Inventory Management
Key → Product ID
Value → Quantity in Stock
Comparison of Map Implementations
Implementation Ordering Performance Null Keys & Values
HashMap No Order Fast O(1) 1 Null Key, Multiple Null
Values
LinkedHashMap Insertion
Order
Slower than
HashMap
Supports Null
TreeMap Sorted Order O(log N) No Null Keys, Supports Null
Values
Conclusion
The Map interface is best when:
o You want to store unique keys mapped to values.
o You need different implementations for sorting or insertion order.