Java Collections Framework
Java Collections Framework
A Collection is a group of objects (like a container). The Java Collections Framework (JCF)
provides:
Iterable
|
Collection
________/ \________
| |
List Set Map (separate hierarchy)
/ \ / \ / \
ArrayList LinkedList HashSet TreeSet HashMap TreeMap
✏ 5. Examples
// List Example
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names); // Output: [Alice, Bob]
// Set Example
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(10); // Duplicate ignored
System.out.println(numbers); // Output: [10]
// Map Example
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
System.out.println(scores); // Output: {Alice=90, Bob=85}
Q2. Add 5 numbers to a HashSet (including duplicates) and print unique numbers.
Q3. Store 3 names with marks in a HashMap and print all key-value pairs.
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
✅ Q3. Store 3 names with marks in a HashMap and print all key-value pairs
import java.util.HashMap;
import java.util.Map;
public class StudentScores {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Array to ArrayList
String[] colors = {"Yellow", "Pink", "Black"};
List<String> newList = new ArrayList<>(Arrays.asList(colors));
System.out.println("ArrayList: " + newList);
}
}
Day 2: List Interface in Java
● Duplicates
🔧 Internal Working:
● Backed by an array.
● Subclass of Vector
🎯 6. Interview Questions
1. ArrayList vs LinkedList
4.
📘 7. Diagrams
📌 ArrayList
[Index] 0 1 2
[A] [B] [C]
📌 LinkedList
NULL <- [A] <-> [B] <-> [C] -> NULL
📌 Stack
Top -> [C]
[B]
[A]
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.LinkedList;
import java.util.Stack;
import java.util.Enumeration;
import java.util.Vector;
Enumeration<String> e = animals.elements();
System.out.println("Vector elements:");
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
}
🔹 1. What is a Set?
● A Set is a collection that does not allow duplicate elements.
Allows Duplicates? No No No
Null Allowed? One null One null element Null not allowed
element
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
📘 6. Diagrams
📌 TreeSet (Sorted)
30
/ \
10 50
🎯 7. Interview Questions
1. HashSet vs TreeSet?
Q1. Add 10 random integers (including duplicates) to a HashSet and print unique
numbers.
Q3. Create a TreeSet of strings and show how they are auto-sorted.
Q4. Find the first repeated and first non-repeated element in a list using Set and Map
together.
import java.util.HashSet;
import java.util.Set;
import java.util.LinkedHashSet;
✅ Q3. Create a TreeSet of strings and show how they are auto-sorted
import java.util.TreeSet;
public class SortedStrings {
public static void main(String[] args) {
TreeSet<String> animals = new TreeSet<>();
animals.add("Zebra");
animals.add("Elephant");
animals.add("Monkey");
animals.add("Dog");
✅ Q4. Find the first repeated and first non-repeated element in a list using
Set and Map
import java.util.*;
🔹 1. What is a Map?
● No duplicate keys
Thread-safe No No No
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
🧠 5. Diagram Representation
📌 HashMap
(Key -> Value)
"A" -> 90
"B" -> 85
(no order)
📌 LinkedHashMap
Insertion order:
3->C → 1->A → 2->B
📌 TreeMap
Sorted by Key:
Apple -> 2 → Mango -> 3 → Zebra -> 5
🎯 6. Interview Questions
1. HashMap vs TreeMap
Q1. Create a HashMap with names and marks. Print all entries.
Q2. Create a LinkedHashMap with 5 cities and their PIN codes. Show that order is
maintained.
Q3. Create a TreeMap with employee names and their salaries. Show sorted order.
✅ Q1. Create a HashMap with names and marks. Print all entries
import java.util.HashMap;
import java.util.Map;
✅ Q2. Create a LinkedHashMap with 5 cities and their PIN codes. Show
that order is maintained
import java.util.LinkedHashMap;
import java.util.Map;
✅ Q3. Create a TreeMap with employee names and their salaries. Show
sorted order
import java.util.Map;
import java.util.TreeMap;
import java.util.HashMap;
import java.util.Map;
System.out.println("Character Frequencies:");
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
System.out.println(entry.getKey() + ": " +
entry.getValue());
}
}
}
🔹 1. What is a Queue?
A Queue is a linear data structure that follows the FIFO (First-In-First-Out) principle.
🔹 2. What is a Deque?
A Deque (Double Ended Queue) allows insertion and removal from both ends.
● ArrayDeque
● LinkedList
📌 4. LinkedList as Queue
import java.util.LinkedList;
import java.util.Queue;
import java.util.PriorityQueue;
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " "); // 10 30 40
}
}
}
import java.util.ArrayDeque;
import java.util.Deque;
🔍 7. Diagrams
Queue (FIFO):
Front → [A] → [B] → [C] → Rear
Deque:
PriorityQueue (Min-Heap):
10
/ \
30 40
🎯 8. Interview Questions
1. PriorityQueue vs TreeSet?
2. ArrayDeque vs LinkedList?
○ ArrayDeque is faster, uses resizable array, no memory overhead
○ Stack and Vector are legacy, slower, and synchronized (rarely needed)
○ Palindrome checking
○ LRU Cache
import java.util.*;
import java.util.*;
public class Top3Numbers {
public static void main(String[] args) {
int[] nums = {5, 12, 11, 8, 10, 14, 3, 7};
// Min-heap of size 3
PriorityQueue<Integer> pq = new PriorityQueue<>();
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.ArrayDeque;
import java.util.Deque;
🔹 1. What is a List?
○ ArrayList
○ LinkedList
○ Vector
Backing Data Dynamic array Doubly Linked List Dynamic array Extends Vector
(LIFO stack)
Access Time O(1) random O(n) sequential O(1) random O(1) (top
access access access element)
📌 2. ArrayList Example
import java.util.ArrayList;
📌 3. LinkedList Example
import java.util.LinkedList;
📌 4. Vector Example
import java.util.Vector;
import java.util.Stack;
🧠 6. Diagram Overview
Q1. Create an ArrayList of student names and print size and all names.
Q2. Use LinkedList to add elements at front and end, then remove from front.
Q4. Use Stack to push 3 elements and pop them in LIFO order.
import java.util.ArrayList;
public class StudentList {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add("Alice");
students.add("Bob");
students.add("Charlie");
✅ Q2. LinkedList: add at front and end, then remove from front
import java.util.LinkedList;
import java.util.Stack;
while (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
}
}
}
🔹 1. What is a Set?
📌 3. HashSet Example
import java.util.HashSet;
📌 4. LinkedHashSet Example
import java.util.LinkedHashSet;
import java.util.TreeSet;
🧠 6. Diagram Overview
🎯 7. Interview Questions
Q1. Create a HashSet of integers and add duplicates, then print the set.
Q2. Create a LinkedHashSet and add strings in order; print to verify order.
Q3. Create a TreeSet and add numbers; print to verify sorted order.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
import java.util.HashSet;
set.remove("Python");
System.out.println("After removal: " + set);
🔹 1. What is a Map?
📌 3. HashMap Example
import java.util.HashMap;
import java.util.LinkedHashMap;
📌 5. TreeMap Example
import java.util.TreeMap;
🧠 6. Diagram Overview
● HashMap: Key-value pairs, unordered.
🎯 7. Interview Questions
Q1. Create a HashMap with 3 key-value pairs and print all entries.
Q3. Create a TreeMap with integer keys and print the sorted map.
Q4. Update a value for an existing key in HashMap and print the map.
Day 8 Coding Exercise Solutions
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.TreeMap;
import java.util.HashMap;
🔹 1. What is a Queue?
📌 3. PriorityQueue Example
import java.util.PriorityQueue;
📌 4. ArrayDeque Example
import java.util.ArrayDeque;
System.out.println("ArrayDeque elements:");
while (!deque.isEmpty()) {
System.out.println(deque.poll());
}
}
}
🧠 5. Diagram Overview
🎯 6. Interview Questions
Q1. Create a PriorityQueue of integers, add elements, and print in priority order.
Q2. Use ArrayDeque to add elements at front and rear, then remove and print them.
Q3. Check if PriorityQueue accepts null by adding null element (expect exception).
Q4. Implement a simple queue using ArrayDeque and demonstrate FIFO behavior.
Day 9 Coding Exercise Solutions
import java.util.PriorityQueue;
✅ Q2. ArrayDeque add at front and rear, then remove and print
import java.util.ArrayDeque;
import java.util.PriorityQueue;
import java.util.ArrayDeque;
🔹 1. Collections Class
● Common methods:
○ Collections.sort(List<T>)
○ Collections.reverse(List<T>)
○ Collections.shuffle(List<T>)
○ Collections.max(Collection<T>)
○ Collections.min(Collection<T>)
○ Collections.binarySearch(List<T>, key)
🔹 2. Arrays Class
● Common methods:
○ Arrays.sort(array)
○ Arrays.binarySearch(array, key)
○ Arrays.equals(array1, array2)
○ Arrays.fill(array, value)
○ Arrays.copyOf(array, newLength)
🔹 3. Comparable Interface
● Has method:
int compareTo(T o)
● Example:
@Override
public int compareTo(Student other) {
return this.id - other.id; // sort by id ascending
}
}
🔹 4. Comparator Interface
● Defines custom ordering.
● Has method:
int compare(T o1, T o2)
● Example:
import java.util.Comparator;
🎯 5. Interview Questions
Q3. Sort the same list of Student objects by name using Comparator.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Override
public int compareTo(Student other) {
return this.id - other.id;
}
@Override
public String toString() {
return id + ": " + name;
}
}
Collections.sort(students);
System.out.println("Students sorted by id:");
for (Student s : students) {
System.out.println(s);
}
}
}
✅ Q3. Sort the same list of Student objects by name using Comparator
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Collections.shuffle(list);
System.out.println("Shuffled list: " + list);
}
}
Java Collections Interview Questions & Tips Summary
1. Core Concepts
2. List Interface
3. Set Interface
5. Queue Interface
● What is PriorityQueue?
Elements are ordered by priority (natural order or Comparator).
6. Comparable vs Comparator
7. Performance Tips
● Use ArrayList if you need fast random access and fewer insertions/removals.
● Use HashSet or HashMap for fastest lookup; use TreeSet or TreeMap if you need
sorted data.
● Avoid using Vector and Hashtable unless thread safety is required (prefer
Collections.synchronizedXXX or ConcurrentHashMap).
● Arrays.sort(), Arrays.binarySearch().