Skip to Content
Course content

46: HashMap, TreeMap, and LinkedHashMap

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've likely reached the point in your Java journey where you need to associate one piece of data with another—like a User ID mapped to a User object. At first glance, HashMap, TreeMap, and LinkedHashMap all look like they do the exact same thing: they implement the Map interface. Because of that, a lot of developers assume they are interchangeable and just pick one at random, or stick with HashMap for everything.

"But I put the items in this order!"

The most common misconception I see is the belief that a HashMap remembers the order in which you inserted your keys. It doesn't. Not even close. It uses a hashing function to distribute keys across buckets for maximum speed, and that process completely ignores your insertion sequence.

Map<String, Integer> inventory = new HashMap<>();
inventory.put("Iron Sword", 1);
inventory.put("Health Potion", 10);
inventory.put("Wooden Shield", 1);
inventory.put("Mana Elixir", 5);

// You might expect: Iron Sword, Health Potion, Wooden Shield, Mana Elixir
System.out.println(inventory); 
// Actual output might be: {Mana Elixir=5, Iron Sword=1, Wooden Shield=1, Health Potion=10}

If you're building a UI where the order of items matters, using a HashMap will lead to a bug that's frustratingly intermittent—sometimes the order looks right by coincidence, and other times it's a complete jumble. I've spent way too many hours debugging "random" UI jumps because someone used a HashMap where they needed stability.

Picking the Right Tool for the Job

The real difference between these three isn't what they store, but how they organize that storage. Depending on your needs, you'll choose one of these three strategies.

  • HashMap: This is your "go-to" for raw performance. It offers O(1) time complexity for basic operations. If you don't care about the order of your keys and just want the fastest possible lookup, use this.
  • LinkedHashMap: Think of this as a HashMap with a double-linked list running through it. It maintains insertion order. If you put "Sword" then "Shield", they will stay in that order when you iterate over the map. It's slightly slower and uses more memory than a HashMap, but it's a lifesaver for caches or history lists.
  • TreeMap: This one doesn't care when you inserted the item; it cares about the natural order of the keys (or a custom Comparator you provide). It stores keys in a red-black tree, meaning your keys are always sorted. This is O(log n) performance—slower than the others, but it allows you to do things like "give me all keys between 'A' and 'F'".

Here is how they look side-by-side using the same data:

Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();

String[] items = {"Zebra", "Apple", "Mango"};
for(String s : items) {
    hash.put(s, 1);
    linked.put(s, 1);
    tree.put(s, 1);
}

System.out.println("HashMap: " + hash);     // Unpredictable order
System.out.println("LinkedHashMap: " + linked); // [Zebra, Apple, Mango]
System.out.println("TreeMap: " + tree);     // [Apple, Mango, Zebra]

My rule of thumb? Default to HashMap. If you realize you need to iterate in the order you added things, switch to LinkedHashMap. If you need the keys to be sorted alphabetically or numerically, go with TreeMap.




📋 Practical Task

Build a Sorted Player Inventory System

You are building a gear management system for an RPG. The game requires two different views of the player's inventory:

  1. The "Recent Items" View: A list of items shown in the exact order they were picked up.
  2. The "Alphabetical Archive" View: A list of all items sorted by their name.

Your Task:

  • Create a class called InventoryManager.
  • Implement a method addItem(String itemName, int quantity) that adds the item to both a LinkedHashMap and a TreeMap.
  • Implement a method printRecentItems() that prints the contents of the LinkedHashMap.
  • Implement a method printAlphabeticalItems() that prints the contents of the TreeMap.
  • In your main method, add the following items in this specific order: "Healing Herb", "Ancient Map", "Steel Plate", and "Bronze Key".
  • Call both print methods and verify that the "Recent" view maintains the insertion order while the "Alphabetical" view is sorted A-Z.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.