Skip to main content
Collections framework · Topic 4 of 8

Map types

Definition​

A Map stores key-value pairs with unique keys. HashMap is fast with no order, LinkedHashMap remembers insertion order, and TreeMap keeps keys sorted. The choice is again about the order you need.

Example code​

Iterating the same data in three orders

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

class Demo {
static void fill(Map<String, Integer> map) {
map.put("pear", 3);
map.put("apple", 5);
map.put("fig", 2);
}

public static void main(String[] args) {
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> sorted = new TreeMap<>();
fill(hash);
fill(linked);
fill(sorted);

System.out.println("linked: " + linked); // insertion order
System.out.println("sorted: " + sorted); // sorted by key
System.out.println("apple -> " + hash.get("apple"));
}
}

// Output:
// linked: {pear=3, apple=5, fig=2}
// sorted: {apple=5, fig=2, pear=3}
// apple -> 5

Finished this page? Track your progress (saved only in your browser).