🧰 Java Collections

MrugankMrugank
4 min read

Think of coding without collections like building furniture without tools. You could do it… but why suffer? Let’s explore Java Collections with relatable examples, practical code, and clarity that sticks.


👋 Meet the Java Collections Framework

Imagine you're organizing a party:

  • You have a guest list → that’s a List.

  • You don’t want duplicate names → use a Set.

  • You’re pairing names with RSVPs → that’s a Map.

  • And guests arrive in a queue → well, that’s a Queue.

Java Collections Framework gives you these exact tools for handling groups of data. Instead of reinventing the wheel every time, you use the right structure for the right job.


🧠 Why Should You Care?

Because choosing the right data structure makes your code:

✅ Faster
✅ Cleaner
✅ Easier to debug
✅ Scalable for real-world apps

Let’s skip the theory overload and go straight into understanding through examples.


🧪 Real-World Use Case: Build a Library App

Scenario: You're building a library app that categorizes books by genre.

Here’s how we approach it:

  • We want to group books by genre → use a Map

  • Each genre can have multiple books → use a List for values

📦 Code Walkthrough

javaCopyEditimport java.util.*;

public class Library {
    private Map<String, List<String>> genreToBooks = new HashMap<>();

    public void addBook(String genre, String book) {
        genreToBooks
            .computeIfAbsent(genre, k -> new ArrayList<>())
            .add(book);
    }

    public void showLibrary() {
        genreToBooks.forEach((genre, books) ->
            System.out.println(genre + ": " + books)
        );
    }

    public static void main(String[] args) {
        Library lib = new Library();
        lib.addBook("Sci-Fi", "Dune");
        lib.addBook("Sci-Fi", "Neuromancer");
        lib.addBook("Fantasy", "The Hobbit");
        lib.showLibrary();
    }
}

Output:

makefileCopyEditSci-Fi: [Dune, Neuromancer]
Fantasy: [The Hobbit]

Simple, readable, and effective.


💡 Choosing the Right Collection (Without Going Crazy)

You’re standing in front of the collection toolbox. Here’s when to grab what:

GoalUse ThisWhy
Maintain order, allow duplicatesList (e.g., ArrayList)Like a playlist
No duplicates, order doesn’t matterSet (e.g., HashSet)Like usernames
Key-value lookupMap (e.g., HashMap, TreeMap)Like a dictionary
Process tasks by order or priorityQueue, PriorityQueueLike customer support

🔁 Analogy alert:

  • HashMap is like a messy drawer: fast to grab stuff, but no guarantee of order.

  • TreeMap is like a sorted file cabinet: slower, but always neat.


🛑 Common Gotchas (and How to Avoid Them)

❌ Mistake: Calling .get() without checking the key

javaCopyEditList<String> books = genreToBooks.get("Mystery");
books.add("Sherlock Holmes"); // 💥 Boom! NullPointerException

✅ Fix:

javaCopyEditgenreToBooks.computeIfAbsent("Mystery", k -> new ArrayList<>()).add("Sherlock Holmes");

❌ Mistake: Assuming HashMap keeps order

javaCopyEdit// Nope. Order of keys is NOT guaranteed.

✅ Fix: Use LinkedHashMap if you want insertion order, or TreeMap for sorted order.


🤔 Quick Quiz (Try Answering in Your Head)

  1. When would you choose a PriorityQueue?

  2. Why might a Set silently drop your data?

  3. What makes synchronizedMap() thread-safe, but still risky?

💡 Tap to Reveal Answers
1. When processing tasks that need to be handled by importance (not arrival time). 2. It doesn't allow duplicates—if you add the same item twice, it just skips it. 3. Collections.synchronizedMap() wraps each method with a synchronized block, but iteration still needs external synchronization.

🔄 Summary

Java Collections aren’t just “advanced stuff”—they’re your daily-use essentials. Once you understand the strengths and trade-offs of each, you’ll code more confidently and efficiently.

📘 TL;DR :

  • List = ordered, duplicates allowed

  • Set = unordered, no duplicates

  • Map = key-value storage

  • Queue = first in, first out (or by priority)


🔥 Call to Action

You’ve seen it in action—now it’s your turn:

✅ Modify the library to allow removing books
✅ Add a feature to count how many books each genre has
✅ Try switching HashMap to TreeMap and observe the difference

💬 Leave a comment: What’s your favorite collection type and why?

2
Subscribe to my newsletter

Read articles from Mrugank directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mrugank
Mrugank