Java Academy Logo

Map Implementations in Java

Understanding HashMap, LinkedHashMap, TreeMap, and Hashtable

What are Map Implementations?

Map implementations in Java store key-value pairs, allowing you to quickly retrieve values using their associated keys. Each implementation differs in ordering behavior, null handling, and thread-safety. Understanding these differences helps you choose the right Map for your application.

1

HashMap

Simple explanation

  • Stores key–value pairs
  • Fast lookup
  • No order guaranteed

Example

HashMapExample.java
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");

System.out.println(map);
// Example output (order random): {2=Banana, 1=Apple, 3=Cherry}
2

LinkedHashMap

Simple explanation

  • Same as HashMap, but keeps the insertion order

Example

LinkedHashMapExample.java
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");

System.out.println(map);
// Output: {1=Apple, 2=Banana, 3=Cherry}
3

TreeMap

Simple explanation

  • Stores keys in sorted (ascending) order
  • Sorting happens automatically

Example

TreeMapExample.java
Map<Integer, String> map = new TreeMap<>();
map.put(3, "Cherry");
map.put(1, "Apple");
map.put(2, "Banana");

System.out.println(map);
// Output: {1=Apple, 2=Banana, 3=Cherry} (sorted by key)
4

Hashtable

Simple explanation

  • Like HashMap, but thread-safe
  • Legacy (old), rarely used now
  • Does NOT allow null keys or values

Example

HashtableExample.java
Map<Integer, String> map = new Hashtable<>();
map.put(1, "Apple");
map.put(2, "Banana");

System.out.println(map);
// Output: {2=Banana, 1=Apple}

Quick Summary Table

Map TypeOrder?Allows null?Thread-safe?Notes
HashMapNo orderYesNoFast, most used
LinkedHashMapInsertion orderYesNoPredictable order
TreeMapSorted by keyNo (rare cases)NoUses Red-Black Tree
HashtableNo orderNoYesOld, replaced by ConcurrentHashMap

Key Differences at a Glance

HashMap

Fastest

Random order

Allows null

LinkedHashMap

Insertion order

Predictable

Allows null

TreeMap

Auto-sorted

By key

No null keys

Hashtable

Thread-safe

Legacy

No nulls

When to Use Each Map?

Use HashMap when:

You need fast lookups and don't care about order

Use LinkedHashMap when:

You need to maintain insertion order while still having fast access

Use TreeMap when:

You need keys automatically sorted in ascending order

Use Hashtable when:

You're working with legacy code (otherwise use ConcurrentHashMap for thread-safety)