Question
In Java, what is the difference between HashMap, LinkedHashMap, and TreeMap?
I do not notice much difference in the output because all three provide methods like keySet() and values().
I also want to understand what Hashtable is.
Here is the example code:
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
Map<String, String> m1 = new HashMap<>();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
System.out.println(m1.keySet());
System.out.println(m1.values());
SortedMap<String, String> sm = new TreeMap<>();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
System.out.println(sm.keySet());
System.out.println(sm.values());
LinkedHashMap<String, String> lm = new LinkedHashMap<>();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
System.out.println(lm.keySet());
System.out.println(lm.values());
Why can the printed results look similar in simple examples, and what are the actual differences between these map implementations?
Short Answer
By the end of this page, you will understand how HashMap, LinkedHashMap, TreeMap, and Hashtable differ in Java. You will learn how they store entries, whether they preserve order, how they handle null, and when each one is the right choice.
Concept
A Map in Java stores data as key-value pairs. The key is used to look up the value.
All of these classes implement the Map interface, so they share common methods such as:
put(key, value)get(key)keySet()values()entrySet()
That is why they can look similar at first.
The real difference is how they store data internally and what guarantees they provide.
HashMap
HashMap stores entries based on the hash of the key.
Key characteristics:
- Does not guarantee iteration order
- Usually provides very fast
put()andget()operations - Allows one
nullkey and multiplenullvalues - Best when you want fast lookup and do not care about order
LinkedHashMap
Mental Model
Think of the three map types like three ways of storing index cards.
HashMap: you throw cards into labeled buckets for fast access. It is efficient, but the cards are not arranged in a human-friendly order.LinkedHashMap: same fast buckets, but you also keep a string connecting cards in the order you added them.TreeMap: you place cards on a shelf in alphabetical order, so they are always sorted.Hashtable: an older locked cabinet version ofHashMap. Safe in simple threaded situations, but older and less commonly used now.
So the main question is not "Do they all have keySet()?" The main question is:
How should the entries be organized, and what behavior do you need?
Syntax and Examples
The common syntax is similar because all of them implement Map.
Basic syntax
Map<String, String> hashMap = new HashMap<>();
Map<String, String> linkedHashMap = new LinkedHashMap<>();
Map<String, String> treeMap = new TreeMap<>();
Example showing ordering differences
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
Map<String, Integer> treeMap = new TreeMap<>();
String[] keys = {"banana", "apple", "cherry"};
for (String key : keys) {
hashMap.put(key, key.length());
linkedHashMap.put(key, key.length());
treeMap.put(key, key.length());
}
System.out.println( + hashMap);
System.out.println( + linkedHashMap);
System.out.println( + treeMap);
}
}
Step by Step Execution
Consider this example:
Map<String, String> map = new LinkedHashMap<>();
map.put("b", "Ball");
map.put("a", "Apple");
map.put("c", "Cat");
map.put("a", "Ant");
System.out.println(map.keySet());
System.out.println(map.values());
Step by step:
-
Create an empty
LinkedHashMap- It starts with no entries.
-
map.put("b", "Ball")- Adds key
bwith valueBall - Map becomes:
{b=Ball}
- Adds key
-
map.put("a", "Apple")- Adds key
awith valueApple - Map becomes:
{b=Ball, a=Apple}
- Adds key
-
map.put("c", "Cat")
Real World Use Cases
When to use HashMap
Use HashMap when you want fast access and do not care about order.
Examples:
- Caching user settings by user ID
- Counting word frequency in a text file
- Mapping product codes to product details
- Looking up configuration values by key
When to use LinkedHashMap
Use LinkedHashMap when you want fast access and predictable iteration order.
Examples:
- Showing form fields in the same order they were configured
- Preserving JSON-like field order for readable output
- Building LRU-style caches using access-order mode
- Keeping log or report data in the order it was inserted
When to use TreeMap
Use TreeMap when sorted keys are important.
Examples:
- Ranking scores by key order
- Storing dates in sorted order
- Producing alphabetical reports
- Range queries such as "all keys from A to M"
When Hashtable appears
You may still see Hashtable in:
- Older Java codebases
Real Codebase Usage
In real codebases, developers usually choose a map implementation based on the behavior they need rather than the interface methods.
Common patterns
1. Fast lookup with HashMap
Map<String, Integer> inventory = new HashMap<>();
inventory.put("PEN", 120);
inventory.put("BOOK", 45);
Used for:
- Lookup tables
- Counters
- ID-to-object mappings
2. Predictable output with LinkedHashMap
Map<String, String> headers = new LinkedHashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
Useful when output order should stay stable for:
- Logs
- Reports
- API payload generation
- Test assertions
3. Sorted processing with TreeMap
Map<String, Integer> scores = new TreeMap<>();
scores.put(, );
scores.put(, );
scores.put(, );
Common Mistakes
1. Assuming HashMap keeps insertion order
Broken assumption:
Map<String, Integer> map = new HashMap<>();
map.put("first", 1);
map.put("second", 2);
map.put("third", 3);
System.out.println(map);
Problem:
- The order may look correct on one run or one JDK version
- But Java does not guarantee that order for
HashMap
Fix:
- Use
LinkedHashMapif order matters
2. Expecting duplicate keys to create multiple entries
Broken code:
Map<String, String> map = new HashMap<>();
map.put("x", "one");
map.put("x", "two");
System.out.println(map);
Result:
{x=two}
Fix:
- Remember that keys are unique
- If you need multiple values per key, use something like
Comparisons
| Feature | HashMap | LinkedHashMap | TreeMap | Hashtable |
|---|---|---|---|---|
| Ordering | No guaranteed order | Insertion order | Sorted by key | No guaranteed order |
| Lookup speed | Fast | Fast | Slower than hash-based maps | Fast, but legacy |
| Null key | Yes, one | Yes, one | No | No |
| Null values | Yes | Yes | Yes | No |
| Thread-safe | No | No | No | Yes, method-level synchronization |
Cheat Sheet
Map<K, V> map = new HashMap<>(); // fast, no order guarantee
Map<K, V> map = new LinkedHashMap<>(); // insertion order
Map<K, V> map = new TreeMap<>(); // sorted by key
Map<K, V> map = new Hashtable<>(); // legacy synchronized map
Rules to remember
- A
Mapstores unique keys - Adding the same key again replaces the old value
keySet()returns keysvalues()returns values in entry iteration orderentrySet()returns key-value pairs
Ordering
HashMap: unspecifiedLinkedHashMap: insertion orderTreeMap: sorted key orderHashtable: unspecified
Null handling
HashMap: 1 key, many values
FAQ
Why do HashMap, LinkedHashMap, and TreeMap all have similar methods?
Because they all implement the Map interface. They expose similar operations but differ in ordering, performance, and null handling.
Why does my HashMap sometimes print in insertion order?
That can happen by chance for a small example, but Java does not guarantee it. You should not rely on that behavior.
Does TreeMap sort by keys or values?
TreeMap sorts by keys, not by values.
Can a map contain duplicate keys?
No. A map keeps unique keys. Adding the same key again replaces its value.
What is the difference between Hashtable and HashMap?
Hashtable is an older synchronized map that does not allow null. HashMap is more common in modern Java and allows null.
Is Hashtable obsolete?
It is still part of Java, but it is considered legacy for most new code.
Mini Project
Description
Build a small Java program that stores student scores using different map implementations and prints the results. This project demonstrates how insertion order, sorted order, and default hash-based storage affect output.
Goal
Create a program that inserts the same student data into HashMap, LinkedHashMap, and TreeMap, then prints each map to compare their behavior.
Requirements
- Create three maps:
HashMap,LinkedHashMap, andTreeMap - Insert the same set of student name/score pairs into all three maps
- Include one duplicate key to show value replacement
- Print each map and its
keySet() - Add a short comment in the code describing the expected ordering behavior
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.