Java Collections Framework Explained in Depth with Examples for Beginners
Java Collections Framework Explained in Depth
Author: Gursehbaj Singh | Blog: DevMode
The Java Collections Framework (JCF) is a set of classes and interfaces that help store and manipulate groups of objects. It makes programming easier and efficient for handling data.
Why Collections Framework?
- Store multiple objects easily
- Perform operations like add, remove, search, sort
- Reusable and easy to maintain
- Built-in methods reduce coding effort
Main Interfaces of Collections
- Collection – root interface
- List – ordered collection (allows duplicates)
- Set – unique elements only
- Map – key-value pairs
- Queue – FIFO operations
1. List Interface
List stores elements in order and allows duplicates.
ArrayList Example
import java.util.ArrayList;
class ListExample {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
list.add("Java"); // duplicate allowed
for(String lang : list) {
System.out.println(lang);
}
}
}
LinkedList Example
import java.util.LinkedList;
LinkedList numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.addFirst(5); // add at start
System.out.println(numbers);
2. Set Interface
Set stores unique elements only. No duplicates allowed.
import java.util.HashSet;
HashSet set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("Java"); // duplicate ignored
for(String s : set) {
System.out.println(s);
}
3. Map Interface
Map stores key-value pairs. Keys are unique.
import java.util.HashMap;
HashMap map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");
for(Integer key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}
4. Queue Interface
Queue stores elements in FIFO order.
import java.util.LinkedList;
import java.util.Queue;
Queue queue = new LinkedList<>();
queue.add("Task1");
queue.add("Task2");
queue.add("Task3");
System.out.println(queue.remove()); // removes first element
5. Stack (LIFO)
import java.util.Stack;
Stack stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.pop()); // removes top element
Collections Utility Class
import java.util.ArrayList;
import java.util.Collections;
ArrayList nums = new ArrayList<>();
nums.add(5);
nums.add(1);
nums.add(10);
Collections.sort(nums);
System.out.println(nums);
Collections.reverse(nums);
System.out.println(nums);
Best Practices
- Use appropriate collection for the task
- Always use interfaces in variable declarations (List
list = new ArrayList<>()) - Prefer generics to avoid type casting
- Use enhanced for loop for easy iteration
Conclusion
The Java Collections Framework simplifies working with groups of objects. Mastering List, Set, Map, Queue, and utility classes like Collections will make you a stronger Java programmer capable of handling real-world projects.
Comments
Post a Comment