Table of Contents
Java Collection Framework: Complete Tutorial for Beginners
The Java Collection Framework is the standard way to store, search, and manage groups of objects in Java. If you have ever used ArrayList or HashMap, you have already used it.
This tutorial covers:
- What a collection and a framework actually mean in Java
- The Collection hierarchy (List, Set, Queue, Map)
- Core methods of the
Collectioninterface - ArrayList, LinkedList, HashSet, HashMap with working code
- Iterators, for-each, and stream-based iteration
- Comparison table, best practices, exercises, and FAQs
What Is a Collection in Java?
- A collection is a single object that holds a group of other objects.
- The Collection Framework is the set of interfaces and classes that create, store, and manipulate those groups.
- It lives in the
java.utilpackage. - It replaces older, inconsistent classes such as
VectorandHashtablewith one common design.
In short: a collection is a resizable, feature-rich alternative to a plain array.
What Is a Framework?
- A framework is a ready-made architecture of classes and interfaces.
- You do not build the structure yourself; you plug your code into it.
- Every class in the framework follows the same method names and contracts.
- Result: learn one collection, and the rest feel familiar.
Java Collection Framework Hierarchy
The framework has two root branches:
- Collection (single values)
- List – ordered, allows duplicates:
ArrayList,LinkedList,Vector,Stack - Set – no duplicates:
HashSet,LinkedHashSet,TreeSet - Queue / Deque – order of processing:
PriorityQueue,ArrayDeque,LinkedList
- List – ordered, allows duplicates:
- Map (key-value pairs, not a child of Collection)
HashMap,LinkedHashMap,TreeMap,Hashtable
Key point for exams: Map does not extend Collection. It is part of the framework, but a separate hierarchy.
Methods of the Collection Interface
Every class that implements Collection supports these methods.
| Method | What It Does |
|---|---|
| add(Object o) | Adds one element to the collection |
| addAll(Collection c) | Adds all elements of another collection |
| remove(Object o) | Removes the first matching element |
| removeAll(Collection c) | Removes all elements present in the given collection |
| removeIf(Predicate filter) | Removes every element matching a condition |
| retainAll(Collection c) | Keeps only the elements present in the given collection |
| contains(Object o) | Returns true if the element exists |
| containsAll(Collection c) | Returns true if all given elements exist |
| clear() | Removes every element |
| size() | Returns the number of elements |
| isEmpty() | Returns true if there are no elements |
| iterator() | Returns an iterator to traverse elements |
| stream() | Returns a sequential stream of the elements |
| parallelStream() | Returns a parallel stream of the elements |
| toArray() | Converts the collection into an array |
| equals(Object o) | Compares two collections for equality |
| hashCode() | Returns the hash code of the collection |
ArrayList
- Backed by a resizable array.
- Fast random access by index (
get(i)). - Slow for inserting or deleting in the middle, because elements shift.
- Best choice when you mostly read data.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println(fruits.get(1)); // Banana
System.out.println(fruits.size()); // 3
fruits.remove("Banana");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
LinkedList
- Backed by a doubly linked list of nodes.
- Fast insert and delete at the start, end, or via an iterator.
- Slow random access, because it walks node by node.
- Also implements
Deque, so it can act as a queue or stack.
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.addFirst(5);
numbers.addLast(30);
System.out.println(numbers); // [5, 10, 20, 30]
System.out.println(numbers.getFirst()); // 5
numbers.removeLast();
for (int num : numbers) {
System.out.println(num);
}
}
}
HashSet
- Implements the
Setinterface, so duplicates are rejected. - Uses hashing, giving near constant-time add, remove, and contains.
- Does not maintain insertion order.
- Use
LinkedHashSetfor insertion order,TreeSetfor sorted order.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Red"); // ignored, duplicate
System.out.println(colors.size()); // 3
System.out.println(colors.contains("Green")); // true
for (String color : colors) {
System.out.println(color);
}
}
}
HashMap
- Stores data as key-value pairs.
- Keys must be unique; values may repeat.
- Allows one null key and multiple null values.
- Best for fast lookup by a unique identifier such as a roll number or email.
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> studentScores = new HashMap<>();
studentScores.put("Alice", 90);
studentScores.put("Bob", 85);
studentScores.put("Charlie", 78);
System.out.println(studentScores.get("Bob")); // 85
System.out.println(studentScores.getOrDefault("Dev", 0)); // 0
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Tip: iterate with entrySet() instead of keySet() plus get(). It avoids a second lookup for every key.
Iterators and the For-Each Loop
Java gives you four ways to traverse a collection.
1. Iterator
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int value = iterator.next();
if (value == 2) {
iterator.remove(); // safe removal
}
}
System.out.println(numbers); // [1, 3]
}
}
2. For-each loop
for (String fruit : fruits) {
System.out.println(fruit);
}
3. forEach with lambda
fruits.forEach(fruit -> System.out.println(fruit));
4. Stream API
fruits.stream()
.filter(f -> f.startsWith("A"))
.forEach(System.out::println);
Rule: never remove an element inside a for-each loop. Use Iterator.remove() or removeIf(), otherwise you get a ConcurrentModificationException.
Which Collection Should You Use?
| Class | Duplicates | Order | Best For |
|---|---|---|---|
| ArrayList | Allowed | Insertion order | Frequent reading and index access |
| LinkedList | Allowed | Insertion order | Frequent insert and delete |
| HashSet | Not allowed | No order | Unique values, fast lookup |
| LinkedHashSet | Not allowed | Insertion order | Unique values with order preserved |
| TreeSet | Not allowed | Sorted | Unique values kept sorted |
| HashMap | Unique keys | No order | Key-based lookup |
| TreeMap | Unique keys | Sorted by key | Sorted key-value data |
Common Mistakes and Best Practices
- Declare with the interface type:
List<String> list = new ArrayList<>(); - Always use generics; raw types cause runtime
ClassCastException. - Override
equals()andhashCode()before putting custom objects in aHashSetor asHashMapkeys. - Do not modify a collection while looping over it with for-each.
- Prefer
ArrayListas the default list; switch toLinkedListonly when profiling proves it helps. - Use
Collections.unmodifiableList()orList.of()when the data should not change. - For multi-threaded code, use
ConcurrentHashMapinstead of a synchronizedHashMap.
Exercise Questions and Answers
Q1. What is the Collection Framework in Java and why does it matter?
It is a unified set of interfaces and classes for storing and manipulating groups of objects. It matters because it gives every data structure a common API, tested implementations, and ready algorithms, so you do not write them from scratch.
Q2. ArrayList vs LinkedList?
ArrayList uses a dynamic array, so index access is fast but middle insertions shift elements. LinkedList uses nodes, so insertions and deletions are cheap but index access must traverse the list.
Q3. Why is HashSet useful?
It rejects duplicates automatically and uses hashing, so add, remove, and contains run in roughly constant time.
Q4. How does HashMap work?
It computes the hash of a key, maps it to a bucket, and stores the key-value pair there. Retrieval repeats the same hash calculation, so lookup by key is very fast.
Q5. Is Map a part of the Collection interface?
No. Map belongs to the Collection Framework but does not extend the Collection interface, because it stores pairs rather than single elements.
FAQs
Which package contains the Collection Framework?java.util
Can a collection store primitive types?
No. Collections store objects only. Primitives are auto-boxed into wrapper classes such as Integer and Double.
What is the difference between Collection and Collections?Collection is an interface. Collections is a utility class with static helper methods such as sort(), reverse(), and shuffle().
Which collection is thread safe?Vector, Hashtable, and the concurrent classes such as ConcurrentHashMap and CopyOnWriteArrayList. The standard ArrayList and HashMap are not.
Is this topic important for interviews?
Yes. Collections is one of the most asked topics in Java interviews for freshers, especially ArrayList vs LinkedList and how HashMap works internally.
Conclusion
- Use List when order matters and duplicates are fine.
- Use Set when values must be unique.
- Use Map when you need lookup by a key.
- Use Queue or Deque when processing order matters.
Practice by rewriting one of your existing programs with a different collection type and comparing the code. That is the fastest way to internalise the difference.
Continue Learning
- Java Tutorial: Basics to Advance
- Linked Lists in Data Structures and Algorithms
- Sorting Algorithms: Merge, Heap and Radix
- Java Interview Questions
- Java Projects with Source Code
java collection framework
java collection methods
java collection examples
java collection w3schools
java collections interview questions
java collection framework diagram
java collection framework documentation
java collections javatpoint
java collection updategadh
java collection
[…] Java Collection […]
[…] Java Collection […]