The Java Collections Framework is a powerful library that provides data structures and algorithms to store, retrieve, and manipulate data efficiently. Whether you're building a simple application or a large-scale system, mastering Java collections is essential.
Core Interfaces in Java Collections
The framework is built around several key interfaces:
- Collection (root interface for List, Set, Queue)
- List – Ordered, allows duplicates
- Set – Unordered, no duplicates
- Queue – FIFO structure
- Map – Key-value pair mapping (not a Collection)
1. List Interface
A List maintains the order of insertion and allows duplicate elements.
Common Implementations:
ArrayList
– Fast random access, slower insert/delete in the middleLinkedList
– Slower access, faster insertion/deletion
Example:
java
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // allows duplicate
2. Set Interface
A Set stores unique elements only. Duplicate elements are not allowed.
Common Implementations:
HashSet
– No ordering, fast lookupLinkedHashSet
– Maintains insertion orderTreeSet
– Sorted order, uses a Red-Black tree
Example:
java
Set<String> countries = new HashSet<>();
countries.add("India");
countries.add("Canada");
countries.add("India"); // ignored
3. Map Interface
A Map stores key-value pairs. Keys must be unique.
Common Implementations:
HashMap
– No order, fast lookupLinkedHashMap
– Maintains insertion orderTreeMap
– Sorted by keysConcurrentHashMap
– Thread-safe for concurrent access
Example:
java
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
4. Queue Interface
A Queue follows the First-In-First-Out (FIFO) principle.
Common Implementations:
LinkedList
– Also implements QueuePriorityQueue
– Elements ordered by priority
Example:
java
Queue<String> queue = new LinkedList<>();
queue.add("Task1");
queue.add("Task2");
queue.poll(); // removes "Task1"
Useful Utility Classes
Collections
: Contains static methods like sort()
, reverse()
, shuffle()
, synchronizedList()
.Arrays
: Provides utility methods for arrays like asList()
and sort()
.
Example:
java
Collections.sort(fruits);
Collections.reverse(fruits);
Best Practices
- Prefer interfaces (
List
, Set
, Map
) over concrete classes. - Choose the right data structure for performance (e.g.,
ArrayList
vs LinkedList
). - Use
Collections.unmodifiableList()
for read-only access. - Be aware of synchronization needs in multithreaded environments.
The Java Collections Framework is a backbone of Java programming. Understanding the behavior and use cases of each type helps you write efficient, clean, and scalable code.