Collections Framework in Java
The Java Collections Framework (JCF) is a powerful set of interfaces and classes for storing groups of objects. From dynamic lists to fast lookups and ordered maps, the JCF gives you ready-made data structures so you can focus on business logic instead of writing arrays and trees by hand.
Key Features
List
Ordered, allows duplicates — ArrayList, LinkedList.
Set
Unordered, no duplicates — HashSet, TreeSet.
Map
Key-value pairs — HashMap, TreeMap, LinkedHashMap.
Queue
FIFO order — ArrayDeque, LinkedList, PriorityQueue.
Iterator
Standard way to traverse collections.
Generics
Type-safe collections via <T>.
Syntax
- Import: import java.util.*;
- Create list: List<Integer> list = new ArrayList<>();
- Create set: Set<String> set = new HashSet<>();
- Create map: Map<String,Integer> map = new HashMap<>();
Collection Quick Reference
| Interface | Common Class | Duplicates | Order |
|---|---|---|---|
| List | ArrayList | Yes | Insertion |
| List | LinkedList | Yes | Insertion |
| Set | HashSet | No | None |
| Set | TreeSet | No | Sorted |
| Map | HashMap | Keys No | None |
| Map | TreeMap | Keys No | Sorted by key |
| Queue | ArrayDeque | Yes | FIFO/Stack |
Detailed Explanation & First Example
Let's start with a hands-on example. The program below shows the core idea behind Collections in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.
import java.util.*;
class Main
{
public static void main(String args[])
{
List list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("Java");
for (String s : list)
System.out.println(s);
}
}
Python
Java
Examples — Beginner to Advanced
The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.
import java.util.*;
class Main
{
public static void main(String args[])
{
Set set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10); // duplicate ignored
System.out.println(set);
}
}
import java.util.*;
class Main
{
public static void main(String args[])
{
Map ages = new HashMap<>();
ages.put("Aman", 22);
ages.put("Riya", 25);
for (Map.Entry e : ages.entrySet())
System.out.println(e.getKey() + " = " + e.getValue());
}
}
Riya = 25
import java.util.*;
class Main
{
public static void main(String args[])
{
List list = new ArrayList<>(Arrays.asList(5, 2, 9, 1, 4));
Collections.sort(list);
System.out.println(list);
}
}
import java.util.*;
class Main
{
public static void main(String args[])
{
TreeSet ts = new TreeSet<>();
ts.add(40); ts.add(10); ts.add(30); ts.add(20);
System.out.println(ts);
}
}
import java.util.*;
class Main
{
public static void main(String args[])
{
List list = Arrays.asList("A", "B", "C");
Iterator it = list.iterator();
while (it.hasNext())
System.out.println(it.next());
}
}
B
C
Notes & Tips
- Use List for ordered data with duplicates.
- Use Set for unique elements.
- Use Map for key → value mapping.
- Always use generics (
<T>) for type safety. - Collections utility offers sort, reverse, shuffle, binarySearch.
Real-World Use Cases
Data Lists
Storing records, users, products in ArrayList.
Fast Lookup
HashMap delivers O(1) average lookups.
Unique Tags
HashSet de-duplicates large datasets.
Task Queue
PriorityQueue and ArrayDeque for job scheduling.
Practice Questions
Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.
- Q1. Remove duplicates from an ArrayList using HashSet.
- Q2. Count word frequency in a sentence using HashMap.
- Q3. Sort an ArrayList in descending order.
- Q4. Implement a stack using ArrayDeque.
- Q5. Iterate a HashMap using both
entrySet()andkeySet().
Interview Questions
These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.
A set of interfaces (List, Set, Map, Queue) and classes (ArrayList, HashSet, HashMap…) that implement common data structures.
ArrayList is backed by an array (fast random access); LinkedList is a doubly-linked list (fast insert/remove).
Hashtable is synchronized and legacy; HashMap is unsynchronized and faster, preferred today.
It relies on hashCode() and equals() of elements.
Fail-fast throws
ConcurrentModificationException on structural change (ArrayList); fail-safe iterates a snapshot (CopyOnWriteArrayList).
FAQ
Most aren't. Use
Collections.synchronizedList() or concurrent collections like ConcurrentHashMap.
No — only objects. Use wrapper classes (Integer, Double) with autoboxing.
Average O(1) for get/put; O(n) worst case for hash collisions.
Java's automatic conversion between a primitive (int) and its wrapper (Integer).
Whenever you need keys sorted in natural or custom order with O(log n) operations.
Common Mistakes to Avoid
Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Collections in Java:
- Forgetting the semicolon
;at the end of statements while using Collections. - Mixing up similar method names — read Java docs before using new APIs related to Collections.
- Ignoring compiler warnings — they often hint at bugs that will appear later in production.
- Hard-coding values that should come from configuration files or environment variables.
- Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
- Skipping unit tests — small tests prevent big regressions, especially around control flow.
At-a-Glance
Best Practices
Follow Conventions
Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.
Write Tests
Cover happy path and edge cases with JUnit before shipping changes to production.
Keep Methods Short
A method should do one thing and fit on a single screen. Refactor when it grows.
Validate Inputs
Never trust user input. Validate at the boundary, fail fast and log meaningfully.
Comment the Why
Comments should explain why a decision was made — not what the code does line by line.
Refactor Often
Small frequent refactors are cheap and safe; big rewrites are risky and expensive.
Pro Tips
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Collections | Collections concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
java.util, java.lang and java.io.
Summary
The Java Collections Framework offers ready-made data structures via List, Set, Map and Queue interfaces. Use ArrayList, HashSet and HashMap for everyday tasks, and reach for TreeSet, TreeMap or concurrent versions when ordering or thread safety are required.