JAVA COLLECTIONS – COMPLETE NOTES
1. What is a Collection?
A Collection in Java is a framework that stores and manipulates groups of objects. Examples:
ArrayList, HashSet, HashMap.
2. Difference: Array vs Collection
Array:
- Fixed size
- Stores only same type
- No in-built methods
Collection:
- Dynamic size
- Stores different types
- Many methods (add, remove, size)
3. Collection Framework Hierarchy
Iterable -> Collection -> List / Set / Queue
Map is separate (key-value pairs)
4. Important Interfaces
List (duplicates allowed, ordered): ArrayList, LinkedList, Vector, Stack
Set (no duplicates): HashSet, LinkedHashSet, TreeSet
Map (key/value): HashMap, LinkedHashMap, TreeMap
5. LIST PROGRAMS
ArrayList Example:
import [Link].*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link]("ArrayList: " + list);
[Link]("Banana");
[Link]("After removing: " + list);
for(String s : list) {
[Link](s);
LinkedList Example:
import [Link].*;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList list = new LinkedList<>();
[Link](10);
[Link](20);
[Link](5);
[Link]("LinkedList: " + list);
6. SET PROGRAMS
HashSet Example:
import [Link].*;
public class HashSetExample {
public static void main(String[] args) {
HashSet set = new HashSet<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("A");
[Link]("HashSet: " + set);
TreeSet Example:
import [Link].*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet<>();
[Link](20);
[Link](5);
[Link](15);
[Link]("Sorted TreeSet: " + set);
7. MAP PROGRAMS
HashMap Example:
import [Link].*;
public class HashMapExample {
public static void main(String[] args) {
HashMap map = new HashMap<>();
[Link](1, "Java");
[Link](2, "Python");
[Link](3, "C++");
[Link]("HashMap: " + map);
[Link]("Value for key 2: " + [Link](2));
for([Link] entry : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
TreeMap Example:
import [Link].*;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap map = new TreeMap<>();
[Link](3, "Mango");
[Link](1, "Apple");
[Link](2, "Banana");
[Link]("Sorted TreeMap: " + map);
}
8. QUEUE PROGRAM
PriorityQueue Example:
import [Link].*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue<>();
[Link](30);
[Link](10);
[Link](20);
[Link]("PriorityQueue: " + q);
[Link]("Poll: " + [Link]());
[Link]("After poll: " + q);