Navigation: Main Tutorial Index | Practice Programs | Previous: Exception Handling | Next: Java 8 Features
The Java Collections Framework (JCF) is a set of interfaces, classes, and utility methods used to store, manage, retrieve, and manipulate groups of objects.
Before Collections, Java developers commonly used arrays to store multiple values. However, arrays have a fixed size, which makes them less flexible.
Collections solve this limitation by providing dynamic data structures.
Consider an array:
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;The array can store only three elements. To store more elements, we need to create another array.
Using an ArrayList:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
System.out.println(numbers);
}
}Output:
[10, 20, 30, 40]
The ArrayList automatically grows when new elements are added.
- Dynamic size.
- Ready-made data structures.
- Easy insertion and deletion.
- Searching and sorting utilities.
- Type safety through Generics.
- Reusable and maintainable code.
- Support for different data organization techniques.
These two terms are different.
| Collection | Collections |
|---|---|
| An interface | A utility class |
| Part of the Collections Framework | Provides utility methods |
| Represents a group of objects | Provides sorting, searching, reversing, etc. |
| Parent interface of List, Set, and Queue | Contains static methods |
Example:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(30);
numbers.add(10);
numbers.add(20);
Collections.sort(numbers);
System.out.println(numbers);
}
}Output:
[10, 20, 30]
Here:
Collectionis an interface.Collectionsis a utility class.ArrayListis a class implementing the List interface.
The Collections Framework provides different interfaces for storing data.
Iterable
|
Collection
|
+------------+------------+
| | |
List Set Queue
| | |
+----+----+ +--+-------+ +----------+
| | | | | | | |
ArrayList | Vector | HashSet | LinkedHashSet PriorityQueue
LinkedList| |
Stack| SortedSet
| |
TreeSet NavigableSet
The Map hierarchy is separate from Collection:
Map
|
+------------+------------+
| | |
HashMap LinkedHashMap SortedMap
|
TreeMap
Important: Map belongs to the Java Collections Framework, but Map does not extend the Collection interface.
The List interface stores elements in an ordered sequence.
- Maintains insertion order.
- Allows duplicate elements.
- Supports index-based access.
- Usually allows multiple null elements, depending on implementation.
Examples of List implementations:
- ArrayList
- LinkedList
- Vector
- Stack
ArrayList is a resizable-array implementation of the List interface.
It automatically increases its capacity when additional elements are inserted.
- Maintains insertion order.
- Allows duplicates.
- Allows null elements.
- Provides fast index-based access.
- Insertion or deletion in the middle may require shifting elements.
- It is not synchronized by default.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ayush");
names.add("Rahul");
names.add("Amit");
names.add("Ayush");
System.out.println(names);
}
}Output:
[Ayush, Rahul, Amit, Ayush]
| Method | Description |
|---|---|
| add() | Adds an element |
| get() | Retrieves an element by index |
| set() | Updates an element |
| remove() | Removes an element |
| size() | Returns the number of elements |
| contains() | Checks whether an element exists |
| indexOf() | Returns the first matching index |
| isEmpty() | Checks whether the list is empty |
| clear() | Removes all elements |
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Adding elements
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
System.out.println("Original List: " + numbers);
// Accessing an element
System.out.println("Element at index 1: " + numbers.get(1));
// Updating an element
numbers.set(1, 25);
// Removing an element by index
numbers.remove(2);
// Checking an element
System.out.println("Contains 10: " + numbers.contains(10));
// Size
System.out.println("Size: " + numbers.size());
System.out.println("Final List: " + numbers);
}
}Output:
Original List: [10, 20, 30, 40]
Element at index 1: 20
Contains 10: true
Size: 3
Final List: [10, 25, 40]
Using a for loop:
for (int i = 0; i < numbers.size(); i++) {
System.out.println(numbers.get(i));
}Using an enhanced for loop:
for (Integer number : numbers) {
System.out.println(number);
}Using an Iterator:
import java.util.Iterator;
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}Using Java 8 forEach:
numbers.forEach(number -> System.out.println(number));LinkedList is a doubly linked list implementation of the List and Deque interfaces.
Each node stores:
- Data.
- Reference to the previous node.
- Reference to the next node.
NULL <- [10] <-> [20] <-> [30] -> NULL
- Maintains insertion order.
- Allows duplicate elements.
- Allows null elements.
- Efficient insertion and deletion at the ends.
- Random index-based access is slower than ArrayList.
- Uses additional memory for node references.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<>();
names.add("Ayush");
names.add("Rahul");
names.add("Amit");
names.addFirst("Rohit");
names.addLast("Vikas");
System.out.println(names);
names.removeFirst();
names.removeLast();
System.out.println("After deletion: " + names);
}
}Output:
[Rohit, Ayush, Rahul, Amit, Vikas]
After deletion: [Ayush, Rahul, Amit]
Vector is a legacy resizable-array implementation of the List interface.
- Maintains insertion order.
- Allows duplicates.
- Allows null values.
- Synchronized methods.
- Automatically grows when required.
- Usually slower than ArrayList in single-threaded situations because of synchronization overhead.
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println(numbers);
System.out.println("Capacity: " + numbers.capacity());
}
}Output:
[10, 20, 30]
Capacity: 10
The default initial capacity of Vector is 10.
Stack is a legacy class that extends Vector and follows the LIFO principle.
LIFO = Last In, First Out
The element inserted last is removed first.
| Method | Description |
|---|---|
| push() | Inserts an element |
| pop() | Removes and returns the top element |
| peek() | Returns the top element without removing it |
| empty() | Checks whether the stack is empty |
| search() | Searches for an element |
+------+
| 30 | <- Top
+------+
| 20 |
+------+
| 10 |
+------+
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Stack: " + stack);
System.out.println("Top: " + stack.peek());
System.out.println("Removed: " + stack.pop());
System.out.println("Final Stack: " + stack);
}
}Output:
Stack: [10, 20, 30]
Top: 30
Removed: 30
Final Stack: [10, 20]
Modern recommendation: Prefer Deque with ArrayDeque for stack operations in new Java code.
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.pop());
System.out.println(stack.peek());
}
}Output:
30
20
Set is an interface that stores unique elements.
It does not allow duplicate elements according to the equals() and hashCode() contract.
- Does not allow duplicate elements.
- Implementations differ in ordering.
- Some implementations allow null values, while others do not.
- Does not provide index-based access.
Main implementations:
- HashSet
- LinkedHashSet
- TreeSet
HashSet stores unique elements using a hash table.
- Does not maintain insertion order.
- Does not allow duplicates.
- Allows one null element.
- Provides efficient average-case insertion, deletion, and lookup.
- Does not guarantee iteration order.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20);
System.out.println(numbers);
System.out.println("Contains 10: " + numbers.contains(10));
}
}Possible Output:
[20, 10, 30]
Contains 10: true
The order may differ because HashSet does not guarantee iteration order.
LinkedHashSet extends HashSet and maintains insertion order.
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<String> cities = new LinkedHashSet<>();
cities.add("Patna");
cities.add("Bangalore");
cities.add("Delhi");
cities.add("Patna");
System.out.println(cities);
}
}Output:
[Patna, Bangalore, Delhi]
TreeSet stores unique elements in sorted order.
By default, it uses natural ordering.
- Stores unique elements.
- Maintains sorted order.
- Does not allow null elements under natural ordering.
- Generally provides O(log n) insertion, deletion, and lookup.
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(50);
numbers.add(10);
numbers.add(40);
numbers.add(20);
numbers.add(10);
System.out.println(numbers);
System.out.println("First: " + numbers.first());
System.out.println("Last: " + numbers.last());
}
}Output:
[10, 20, 40, 50]
First: 10
Last: 50
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Duplicates | No | No | No |
| Ordering | No guarantee | Insertion order | Sorted order |
| Null | One allowed | One allowed | Not with natural ordering |
| Typical operations | O(1) average | O(1) average | O(log n) |
| Internal structure | Hash table | Hash table + linked structure | Balanced search tree |
Queue is an interface used to store elements for processing.
A typical Queue follows FIFO.
FIFO = First In, First Out
The first inserted element is normally removed first.
Front Rear
| |
v v
+------+ +------+ +------+
| 10 | -> | 20 | -> | 30 |
+------+ +------+ +------+
| Method | Description |
|---|---|
| add() | Inserts an element; may throw an exception |
| offer() | Inserts an element; returns false if unsuccessful |
| remove() | Removes the head; throws an exception if empty |
| poll() | Removes the head; returns null if empty |
| element() | Retrieves the head; throws an exception if empty |
| peek() | Retrieves the head; returns null if empty |
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(10);
queue.offer(20);
queue.offer(30);
System.out.println("Queue: " + queue);
System.out.println("Front: " + queue.peek());
System.out.println("Removed: " + queue.poll());
System.out.println("Final Queue: " + queue);
}
}Output:
Queue: [10, 20, 30]
Front: 10
Removed: 10
Final Queue: [20, 30]
PriorityQueue processes elements according to priority rather than insertion order.
By default, the smallest element has the highest priority for natural ordering.
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(40);
queue.offer(10);
queue.offer(30);
queue.offer(20);
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}Output:
10
20
30
40
Important: PriorityQueue's iterator does not guarantee sorted traversal. Repeatedly calling poll() retrieves elements according to priority.
import java.util.Collections;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> queue =
new PriorityQueue<>(Collections.reverseOrder());
queue.add(10);
queue.add(40);
queue.add(20);
queue.add(30);
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}Output:
40
30
20
10
Map stores data in key-value pairs.
Each key must be unique, but multiple keys can have the same value.
- Stores key-value pairs.
- Does not permit duplicate keys.
- Values can be duplicated.
- Provides methods for accessing values through keys.
- Map does not extend the Collection interface.
Key Value
------------------
101 Ayush
102 Rahul
103 Amit
| Method | Description |
|---|---|
| put() | Inserts or updates a key-value pair |
| get() | Retrieves a value by key |
| remove() | Removes an entry |
| containsKey() | Checks whether a key exists |
| containsValue() | Checks whether a value exists |
| keySet() | Returns all keys |
| values() | Returns all values |
| entrySet() | Returns all key-value entries |
| size() | Returns the number of entries |
| clear() | Removes all entries |
HashMap stores key-value pairs using hashing.
- Does not guarantee insertion order.
- Does not allow duplicate keys.
- Allows one null key.
- Allows multiple null values.
- Not synchronized by default.
- Provides average O(1) lookup and insertion under good hash distribution.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Ayush");
students.put(102, "Rahul");
students.put(103, "Amit");
System.out.println(students);
System.out.println("Student 101: " + students.get(101));
students.put(102, "Rohit");
System.out.println("Updated Map: " + students);
}
}Possible Output:
{101=Ayush, 102=Rahul, 103=Amit}
Student 101: Ayush
Updated Map: {101=Ayush, 102=Rohit, 103=Amit}
HashMap iteration order is not guaranteed.
LinkedHashMap maintains insertion order by default.
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(3, "Amit");
map.put(1, "Ayush");
map.put(2, "Rahul");
System.out.println(map);
}
}Output:
{3=Amit, 1=Ayush, 2=Rahul}
LinkedHashMap can also be configured for access-order iteration, which is useful when implementing an LRU cache.
TreeMap stores key-value pairs sorted by keys.
It uses a balanced search tree.
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> students = new TreeMap<>();
students.put(103, "Amit");
students.put(101, "Ayush");
students.put(102, "Rahul");
System.out.println(students);
}
}Output:
{101=Ayush, 102=Rahul, 103=Amit}
| Feature | HashMap | LinkedHashMap | TreeMap |
|---|---|---|---|
| Ordering | No guarantee | Insertion order by default | Sorted by keys |
| Null keys | One allowed | One allowed | Not with natural ordering |
| Duplicate keys | No | No | No |
| Typical lookup | O(1) average | O(1) average | O(log n) |
| Internal structure | Hash table | Hash table + linked structure | Balanced search tree |
Iterators are used to traverse elements in collections.
Iterator provides forward traversal.
Important methods:
hasNext()– checks whether another element exists.next()– returns the next element.remove()– removes the last element returned by next(), if supported.
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}Output:
10
20
30
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
Integer number = iterator.next();
if (number == 20) {
iterator.remove();
}
}
System.out.println(numbers);
}
}Output:
[10, 30, 40]
ListIterator is available only for List implementations.
It supports:
- Forward traversal.
- Backward traversal.
- Adding elements.
- Updating elements.
- Removing elements.
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ayush");
names.add("Rahul");
names.add("Amit");
ListIterator<String> iterator = names.listIterator();
System.out.println("Forward:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println("Backward:");
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
}
}Output:
Forward:
Ayush
Rahul
Amit
Backward:
Amit
Rahul
Ayush
| Iterator | ListIterator |
|---|---|
| Works with collections | Works only with Lists |
| Forward traversal | Forward and backward traversal |
| Supports remove() | Supports remove(), add(), and set() |
| No index information | Provides nextIndex() and previousIndex() |
Fail-fast behavior: Many standard collection iterators are fail-fast. Structural modification outside the iterator during iteration may cause ConcurrentModificationException. This is best-effort behavior, not a thread-safety guarantee.
Comparable and Comparator are used to define sorting order.
Comparable defines the natural ordering of objects.
It is implemented by the class whose objects need to be compared.
It contains:
int compareTo(T object);import java.util.ArrayList;
import java.util.Collections;
class Student implements Comparable<Student> {
int marks;
String name;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
public int compareTo(Student other) {
return Integer.compare(this.marks, other.marks);
}
public String toString() {
return name + " - " + marks;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Ayush", 85));
students.add(new Student("Rahul", 70));
students.add(new Student("Amit", 90));
Collections.sort(students);
for (Student student : students) {
System.out.println(student);
}
}
}Output:
Rahul - 70
Ayush - 85
Amit - 90
Comparator defines custom sorting logic outside the class.
It contains:
int compare(T object1, T object2);import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
public String toString() {
return name + " - " + marks;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Ayush", 85));
students.add(new Student("Rahul", 70));
students.add(new Student("Amit", 90));
Comparator<Student> byName =
(s1, s2) -> s1.name.compareTo(s2.name);
Collections.sort(students, byName);
for (Student student : students) {
System.out.println(student);
}
}
}Output:
Amit - 90
Ayush - 85
Rahul - 70
| Comparable | Comparator |
|---|---|
| Defines natural ordering | Defines custom ordering |
| Uses compareTo() | Uses compare() |
| Implemented inside the class | Can be defined outside the class |
| Usually one natural order | Multiple sorting strategies possible |
Generics allow classes and interfaces to work with specified data types.
They provide compile-time type safety.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Ayush");
list.add(100);
String name = (String) list.get(0);
System.out.println(name);
}
}Raw collections can store different types, so incorrect values may cause runtime errors.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ayush");
names.add("Rahul");
// names.add(100); // Compilation error
for (String name : names) {
System.out.println(name);
}
}
}Output:
Ayush
Rahul
- Type safety.
- Fewer explicit type casts.
- Errors detected at compile time.
- More reusable code.
- Better readability.
Java 8 introduced useful methods and lambda-based operations.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList(
"Ayush", "Rahul", "Amit"
);
names.forEach(name -> System.out.println(name));
}
}Output:
Ayush
Rahul
Amit
Removes elements matching a condition.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
numbers.add(30);
numbers.removeIf(number -> number % 2 != 0);
System.out.println(numbers);
}
}Output:
[10, 20, 30]
Returns the value associated with a key, or a default value if the key is absent.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Ayush");
System.out.println(students.getOrDefault(101, "Unknown"));
System.out.println(students.getOrDefault(102, "Unknown"));
}
}Output:
Ayush
Unknown
Adds a mapping only if the key does not already have a non-null value.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Ayush");
students.putIfAbsent(101, "Rahul");
students.putIfAbsent(102, "Amit");
System.out.println(students);
}
}Output:
{101=Ayush, 102=Amit}
Computes and inserts a value when a key is absent or currently mapped to null.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.computeIfAbsent(101, key -> "Ayush");
students.computeIfAbsent(102, key -> "Rahul");
System.out.println(students);
}
}Output:
{101=Ayush, 102=Rahul}
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Ayush");
students.put(102, "Rahul");
students.put(103, "Amit");
students.forEach((id, name) ->
System.out.println(id + " : " + name)
);
}
}Output:
101 : Ayush
102 : Rahul
103 : Amit
The displayed iteration order is not guaranteed for HashMap.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] names = {"Ayush", "Rahul", "Amit"};
List<String> list = Arrays.asList(names);
System.out.println(list);
}
}Output:
[Ayush, Rahul, Amit]
Important: Arrays.asList() returns a fixed-size list backed by the original array. You can use set(), but add() and remove() are unsupported.
To create a resizable ArrayList:
List<String> list = new ArrayList<>(Arrays.asList(names));import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ayush");
names.add("Rahul");
String[] array = names.toArray(new String[0]);
for (String name : array) {
System.out.println(name);
}
}
}Output:
Ayush
Rahul
| Array | ArrayList |
|---|---|
| Fixed size | Dynamic size |
| Stores primitives and objects | Stores objects; primitives use wrapper classes |
| Uses length | Uses size() |
| Built-in language feature | Collections Framework class |
| Can be multidimensional | Can contain other lists |
| ArrayList | LinkedList |
|---|---|
| Resizable array | Doubly linked list |
| Fast indexed access | Slower indexed access |
| Middle insertion may require shifting | Insertion after reaching a node does not require shifting |
| Less memory overhead per element | More memory for node references |
| Not synchronized | Not synchronized |
| List | Set |
|---|---|
| Allows duplicates | Does not allow duplicates |
| Maintains positional order | Ordering depends on implementation |
| Supports index-based access | No index-based access |
| Queue | Stack |
|---|---|
| Usually FIFO | LIFO |
| Insert at the rear and remove from the head | Insert and remove at the top |
| Examples: scheduling | Examples: undo operations |
| HashMap | Hashtable |
|---|---|
| Not synchronized | Synchronized methods |
| Allows one null key | Does not allow null keys |
| Allows null values | Does not allow null values |
| Generally preferred in non-concurrent code | Legacy class |
For concurrent access, consider ConcurrentHashMap rather than choosing Hashtable for new applications.
import java.util.ArrayList;
class Student {
int id;
String name;
double marks;
Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
public String toString() {
return id + " - " + name + " - " + marks;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(101, "Ayush", 85.5));
students.add(new Student(102, "Rahul", 90.0));
students.add(new Student(103, "Amit", 78.5));
System.out.println("Student Records:");
for (Student student : students) {
System.out.println(student);
}
}
}Output:
Student Records:
101 - Ayush - 85.5
102 - Rahul - 90.0
103 - Amit - 78.5
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String sentence = "java is easy and java is powerful";
String[] words = sentence.split(" ");
HashMap<String, Integer> frequency = new HashMap<>();
for (String word : words) {
frequency.put(
word,
frequency.getOrDefault(word, 0) + 1
);
}
frequency.forEach((word, count) ->
System.out.println(word + " : " + count)
);
}
}Output (order may vary):
java : 2
is : 2
easy : 1
and : 1
powerful : 1
import java.util.ArrayList;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(10);
numbers.add(30);
numbers.add(20);
LinkedHashSet<Integer> unique =
new LinkedHashSet<>(numbers);
ArrayList<Integer> result = new ArrayList<>(unique);
System.out.println(result);
}
}Output:
[10, 20, 30]
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque<String> history = new ArrayDeque<>();
history.push("google.com");
history.push("github.com");
history.push("stackoverflow.com");
System.out.println("Current Page: " + history.peek());
history.pop();
System.out.println("After Back: " + history.peek());
}
}Output:
Current Page: stackoverflow.com
After Back: github.com
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> employees = new TreeMap<>();
employees.put(103, "Amit");
employees.put(101, "Ayush");
employees.put(102, "Rahul");
employees.forEach((id, name) ->
System.out.println(id + " : " + name)
);
}
}Output:
101 : Ayush
102 : Rahul
103 : Amit
- Assuming HashSet maintains insertion order.
- Assuming HashMap maintains insertion order.
- Trying to access Set elements using indexes.
- Using
==instead ofequals()for object-value comparison. - Modifying a collection directly during fail-fast iteration.
- Using raw collections instead of Generics.
- Assuming Arrays.asList() creates a resizable ArrayList.
- Using Stack instead of Deque in new code.
- Assuming PriorityQueue iteration is sorted.
- Forgetting that Map does not extend Collection.
- Using mutable objects as HashMap keys without considering hashCode changes.
- Ignoring the equals() and hashCode() contract when using custom objects in HashSet or HashMap.
Consider:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.remove(1);This removes the element at index 1, which is 20.
To remove the value 20:
numbers.remove(Integer.valueOf(20));This distinction is frequently asked in interviews.
- Use interface references where practical, such as
List<String> names = new ArrayList<>();. - Use Generics for type safety.
- Choose the collection according to the required operations.
- Prefer ArrayList for general-purpose list usage.
- Prefer HashSet when uniqueness matters and ordering does not.
- Prefer LinkedHashSet when uniqueness and insertion order matter.
- Prefer TreeSet when sorted unique elements are required.
- Prefer HashMap for general key-value storage.
- Prefer TreeMap when sorted keys are required.
- Prefer ArrayDeque for stack and queue operations.
- Use ConcurrentHashMap for suitable concurrent key-value operations.
- Override equals() and hashCode() consistently for custom objects used in hash-based collections.
- What is the Java Collections Framework?
Answer: The Java Collections Framework is a set of interfaces and implementations for storing, retrieving, and processing groups of objects.
- Why do we use Collections in Java?
Answer: Collections provide dynamic sizing, useful implementations, type safety through generics, and common search and sort algorithms.
- What is the difference between Collection and Collections?
Answer: Collection is a root interface for element containers; Collections is a utility class with static collection algorithms and wrappers.
- What is the Collection interface?
Answer: The Collection interface defines common operations such as add, remove, contains, size, and iterator.
- What is the difference between List, Set, and Queue?
Answer: List preserves order and allows duplicates, Set stores unique elements, and Queue models ordered element processing.
- What is the difference between an array and an ArrayList?
Answer: Arrays have fixed length and may hold primitives or objects; ArrayList has dynamic capacity and stores objects through generics.
- What is ArrayList?
Answer: ArrayList is a resizable-array List implementation with fast indexed access and amortized-constant-time appends.
- What is LinkedList?
Answer: LinkedList is a doubly linked List and Deque implementation, efficient for operations at or near either end.
- What is HashSet?
Answer: HashSet is a hash-table-based Set that rejects duplicate elements and does not guarantee iteration order.
- What is HashMap?
Answer: HashMap stores key-value pairs in a hash table, provides average O(1) lookup, and allows one null key and multiple null values.
- What is the difference between ArrayList and LinkedList?
Answer: ArrayList is faster for indexed access; LinkedList is efficient for end operations but slower for indexes and has per-node overhead.
- What is the difference between HashSet and TreeSet?
Answer: HashSet is unordered; TreeSet keeps elements in natural or comparator-defined sorted order.
- What is the difference between HashMap and LinkedHashMap?
Answer: HashMap has no iteration-order guarantee; LinkedHashMap maintains insertion order or access order.
- Why does HashMap allow only one null key?
Answer: HashMap permits only one null key because key lookup requires at most one distinct key equal to null; later entries with that key replace its value.
- How does HashMap work internally?
Answer: HashMap hashes the key, chooses a bucket, compares candidates with hashCode() and equals(), and updates or retrieves the entry; Java 8 may treeify long chains.
- What is hashing?
Answer: Hashing converts an object to an integer used to select a hash-table bucket.
- What is a hash collision?
Answer: A collision occurs when different keys have the same hash or bucket; hash-based classes distinguish them using equals().
- What is the difference between Iterator and ListIterator?
Answer: Iterator supports forward traversal; ListIterator supports bidirectional traversal and list element modification.
- What is the difference between Comparable and Comparator?
Answer: Comparable defines natural object ordering with compareTo(); Comparator defines a separate ordering with compare().
- What is the difference between fail-fast and fail-safe terminology in collection iteration?
Answer: Fail-fast iterators detect concurrent structural modification and throw ConcurrentModificationException; fail-safe/weakly consistent views do not promise the newest state and usually do not throw it.
- Explain the internal working of HashMap in Java 8.
Answer: Java 8 HashMap uses a spread key hash to choose a bucket, compares colliding keys with hashCode() and equals(), and represents sufficiently large collision chains as red-black trees.
- What happens when two keys have the same hash code?
Answer: Keys with the same hash remain in the same bucket and are distinguished with equals(); equal keys identify the same entry.
- Why should equals() and hashCode() be overridden together?
Answer: Hash-based collections use hashCode() to select a bucket and equals() to verify equality, so equal objects must have the same hash code.
- How does HashSet internally use HashMap?
Answer: HashSet delegates storage to a HashMap, using the element as a key and a constant placeholder as the value.
- What is the load factor of HashMap?
Answer: The load factor is the capacity-to-entry ratio that triggers resizing; HashMap’s default is 0.75.
- What is the default initial capacity and load factor of HashMap?
Answer: The default initial capacity is 16 buckets and the default load factor is 0.75.
- What is ConcurrentHashMap?
Answer: ConcurrentHashMap is a thread-safe hash table designed for concurrent reads and updates with no whole-map read lock.
- What is the difference between HashMap and ConcurrentHashMap?
Answer: HashMap is unsynchronized and not thread-safe; ConcurrentHashMap is thread-safe, more concurrent, and permits neither null keys nor null values.
- Why is ArrayDeque preferred over Stack?
Answer: ArrayDeque is resizable-array-backed, faster and more memory-efficient than legacy Stack, and supports consistent double-ended operations.
- What is the difference between synchronized collections and concurrent collections?
Answer: Synchronized collections apply broad method locks; concurrent collections use concurrency-aware structures and generally scale better.
Note: Try solving each exercise independently before checking the solution.
Completed solutions are available in the Practice-Programs folder.
- Create an ArrayList of five student names and print all names.
- Write a Java program to add, update, and remove elements from an ArrayList.
- Write a program to find the size of an ArrayList.
- Write a program to check whether a particular element exists in an ArrayList.
- Create a LinkedList and insert elements at the beginning and end.
- Write a program to remove duplicate elements using HashSet.
- Create a LinkedHashSet and demonstrate insertion order.
- Create a TreeSet and display elements in sorted order.
- Create a HashMap to store student IDs and names.
- Write a program to retrieve a value from a HashMap using its key.
- Write a program to sort an ArrayList in ascending order.
- Write a program to sort an ArrayList in descending order.
- Write a program to find the second-largest element in an ArrayList.
- Write a program to find the frequency of each element in an ArrayList.
- Write a program to count the frequency of words in a sentence using HashMap.
- Write a program to remove all even numbers from an ArrayList.
- Write a program to merge two ArrayLists.
- Write a program to find common elements between two ArrayLists.
- Write a program to convert an array into an ArrayList.
- Write a program to traverse a LinkedList using Iterator and ListIterator.
- Create a Student class and sort students using Comparable based on marks.
- Create a Student class and sort students using Comparator based on names.
- Implement a stack using ArrayDeque.
- Implement a queue using LinkedList.
- Implement a priority queue to process tasks based on priority.
- Create a word-frequency counter using HashMap.
- Create an employee management system using ArrayList and HashMap.
- Implement a simple browser history system using Deque.
- Implement an LRU cache using LinkedHashMap.
- Create a custom class and use its objects as keys in a HashMap by correctly implementing equals() and hashCode().
In this chapter, you learned:
- Introduction to Java Collections Framework.
- Collection vs Collections.
- Collections Framework hierarchy.
- List, Set, Queue, and Map.
- ArrayList, LinkedList, Vector, and Stack.
- HashSet, LinkedHashSet, and TreeSet.
- Queue and PriorityQueue.
- HashMap, LinkedHashMap, and TreeMap.
- Iterator and ListIterator.
- Comparable and Comparator.
- Generics.
- Java 8 Collection features.
- Array and Collection conversions.
- Real-world applications and interview questions.
| Requirement | Recommended Collection |
|---|---|
| Dynamic list | ArrayList |
| Frequent operations at both ends | LinkedList or ArrayDeque |
| Unique elements | HashSet |
| Unique elements in insertion order | LinkedHashSet |
| Unique sorted elements | TreeSet |
| Key-value storage | HashMap |
| Key-value storage in insertion order | LinkedHashMap |
| Key-value storage with sorted keys | TreeMap |
| Stack operations | ArrayDeque |
| Priority-based processing | PriorityQueue |
In the next chapter, we will explore:
- Introduction to Java 8.
- Lambda Expressions.
- Functional Interfaces.
- Predicate, Function, Consumer, and Supplier.
- Method References.
- Stream API.
- Filter, Map, Sorted, and Reduce.
- Optional Class.
- Default and Static Methods in Interfaces.
- Date and Time API.
- Collectors and grouping operations.
- Practical Java 8 programs.
- Interview questions and practice exercises.
Keep practicing every concept by writing and executing the programs yourself. Understanding when and why to choose a particular collection is just as important as knowing its methods.