Java Collections
Think of collections as containers to hold objects
➤ a. List – Ordered, allows duplicates
- Real-world: List of users in a chat
javaCopyEditList<String> users = new ArrayList<>();
users.add("Alice");
users.add("Bob");
➤ b. Set – Unordered, no duplicates
- Real-world: Unique usernames
javaCopyEditSet<String> usernames = new HashSet<>();
usernames.add("alice");
usernames.add("alice"); // Ignored
➤ c. Map – Key-value pairs
- Real-world: Phonebook (name → number)
javaCopyEditMap<String, String> phoneBook = new HashMap<>();
phoneBook.put("Alice", "12345");
System.out.println(phoneBook.get("Alice")); // 12345
1. LinkedList
A List that stores elements in a doubly-linked list structure.
✅ Features:
Maintains insertion order
Fast insertion/deletion (especially at the beginning/middle)
🧠 Real-world Analogy:
Think of a chain of train coaches — easy to add/remove between any two but hard to jump directly to the 10th one.
🔧 Example:
javaCopyEditLinkedList<String> queue = new LinkedList<>();
queue.add("Task1");
queue.addFirst("UrgentTask");
queue.removeLast(); // removes "Task1"
🌲 2. TreeSet
A Set that keeps elements sorted and unique, using a Red-Black Tree structure.
✅ Features:
No duplicates (like all Sets)
Sorted in natural order or using a custom comparator
Slower than
HashSet, but sorted!
🧠 Real-world Analogy:
Like a sorted guest list with no duplicate names.
🔧 Example:
javaCopyEditTreeSet<Integer> scores = new TreeSet<>();
scores.add(50);
scores.add(80);
scores.add(70);
System.out.println(scores); // [50, 70, 80]
🧾 3. LinkedHashMap
A Map that maintains the insertion order of keys.
✅ Features:
Fast lookup like
HashMapMaintains order in which keys were inserted
Useful when you want predictable iteration
🧠 Real-world Analogy:
Like a notebook where you write key-value notes in order, and read them back in same order.
🔧 Example:
javaCopyEditLinkedHashMap<String, Integer> marks = new LinkedHashMap<>();
marks.put("Math", 95);
marks.put("Science", 90);
System.out.println(marks); // {Math=95, Science=90}
🌳 4. TreeMap
A Map that sorts keys in natural or custom order
✅ Features:
Keeps keys sorted
No insertion order (uses key ordering)
Slower than
HashMap, but sorted keys
🔧 Example:
javaCopyEditTreeMap<String, Integer> map = new TreeMap<>();
map.put("Zebra", 1);
map.put("Apple", 2);
System.out.println(map); // {Apple=2, Zebra=1}
🔀 5. PriorityQueue
A queue where elements are sorted according to priority
✅ Features:
Default: natural order (min heap)
Used in scheduling, simulations, etc.
🔧 Example:
javaCopyEditPriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(50);
pq.add(20);
pq.add(30);
System.out.println(pq.poll()); // 20 (smallest)
