Convert a List to a Map
Turning a list into a map means choosing a key for each element and deciding what happens when two elements share a key. Collectors.toMap, groupingBy and a plain loop each make that decision differently. This page explains the options, shows the duplicate-key and null traps, builds index and partition maps, and measures how sizing the map affects speed.
Contents
What converting a list to a map involves The basic conversion: toMap and a loop Duplicate keys and the map type Null values and grouping Index maps, positions and partitions Composite keys and nested maps Sizing the map, and how fast each approach is Loops with put, putIfAbsent, merge and computeIfAbsent Which approach to use
What converting a list to a map involves
A list holds elements in order and allows duplicates; a map holds unique keys, each with one value. Converting means answering three questions for every element:
- What is the key? Usually a property such as an ID, extracted with a method reference like
.Product::sku - What is the value? The element itself, another property, or a collection of all elements with that key.
- What happens when two elements produce the same key? This is where the approaches differ most, and where most bugs come from.
The map type matters too: HashMapLinkedHashMapTreeMap
| Approach | Since | Duplicate keys | Best for |
|---|---|---|---|
forput | Java 1.2 | Last value wins silently | Simple code, nulls, custom rules |
Collectors.toMap(key, value) | Java 8 | Throws IllegalStateException | Keys known to be unique |
toMap(key, value, merge) | Java 8 | The merge function decides | Summing, keeping first or last |
toMap(key, value, merge, mapFactory) | Java 8 | The merge function decides | A specific map type |
Collectors.groupingBy | Java 8 | Collected into a list or other result | Keeping all elements per key |
Collectors.partitioningBy | Java 8 | Two keys only: true and false | Splitting by a condition |
Collectors.toUnmodifiableMap | Java 10 | Throws | Read-only results |
The examples ran on JDK 21. For the reverse direction, see
The basic conversion: toMap and a loop
Three products with unique SKUs are the simple case, where every approach gives the same map.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ToMapBasics {
record Product(String sku, String name, double price) {
}
public static void main(String[] args) {
List<Product> products = List.of(
new Product("A1", "Keyboard", 49.0),
new Product("B7", "Mouse", 19.5),
new Product("C3", "Monitor", 189.0));
// key = sku, value = the whole product
Map<String, Product> bySku = products.stream()
.collect(Collectors.toMap(Product::sku, Function.identity()));
System.out.println("B7 -> " + bySku.get("B7").name());
// key = name, value = price
Map<String, Double> priceByName = products.stream()
.collect(Collectors.toMap(Product::name, Product::price));
System.out.println("Monitor costs " + priceByName.get("Monitor"));
// The same thing with a plain loop, no streams
Map<String, Product> loopMap = new HashMap<>();
for (Product p : products) {
loopMap.put(p.sku(), p);
}
System.out.println("loop map has " + loopMap.size() + " entries");
}
}
Output:
B7 -> Mouse
Monitor costs 189.0
loop map has 3 entries
maps each SKU to its product, the usual way to build a lookup table by ID.toMap(Product::sku, Function.identity()) keeps only one property as the value.toMap(Product::name, Product::price)- The loop gives the same result and is just as good. Choose the stream when the conversion is part of a longer pipeline, and the loop when the logic per element is more than one line.
Duplicate keys and the map type
Orders from the same customer share a key, which is the situation where the default toMap
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class DuplicatesAndOrder {
record Order(String customer, int amount) {
}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("zoe", 30), new Order("ali", 50),
new Order("zoe", 20), new Order("max", 10));
// 1. Duplicate keys throw by default
try {
orders.stream().collect(Collectors.toMap(Order::customer, Order::amount));
} catch (IllegalStateException e) {
System.out.println("no merge function: " + e.getMessage());
}
// 2. A merge function decides what to do with a clash: here, add the amounts
Map<String, Integer> totals = orders.stream()
.collect(Collectors.toMap(Order::customer, Order::amount, Integer::sum));
System.out.println("summed (HashMap): " + totals);
// 3. Keep the first value seen instead
Map<String, Integer> first = orders.stream()
.collect(Collectors.toMap(Order::customer, Order::amount, (a, b) -> a));
System.out.println("keep first: " + first);
// 4. The fourth argument picks the map type: insertion order or sorted
Map<String, Integer> inOrder = orders.stream()
.collect(Collectors.toMap(Order::customer, Order::amount,
Integer::sum, LinkedHashMap::new));
System.out.println("LinkedHashMap: " + inOrder);
Map<String, Integer> sorted = orders.stream()
.collect(Collectors.toMap(Order::customer, Order::amount,
Integer::sum, TreeMap::new));
System.out.println("TreeMap: " + sorted);
}
}
Output:
no merge function: Duplicate key zoe (attempted merging values 30 and 20)
summed (HashMap): {zoe=50, max=10, ali=50}
keep first: {zoe=30, max=10, ali=50}
LinkedHashMap: {zoe=50, ali=50, max=10}
TreeMap: {ali=50, max=10, zoe=50}
- Without a merge function, the second order for
threwzoe . Since Java 9 the message names the key and both values, which makes the bad data easy to find. A loop withIllegalStateException would instead have kept 20 and silently dropped 30.put as the merge function adds the amounts, giving 50 forInteger::sum ;zoe keeps the first value seen.(a, b) -> a- The default result is a
, whose order depends on hash codes. The fourth argument,HashMap orLinkedHashMap::new , gives insertion order or sorted keys. The map type can only be chosen together with a merge function.TreeMap::new
Null values and grouping
A user without an email has a null
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class NullsAndGrouping {
record User(String id, String email) {
}
public static void main(String[] args) {
List<User> users = List.of(new User("u1", "a@x.io"), new User("u2", null));
// toMap rejects null VALUES (it uses HashMap.merge internally)
try {
users.stream().collect(Collectors.toMap(User::id, User::email));
} catch (NullPointerException e) {
System.out.println("toMap with null value: NullPointerException");
}
// A loop, or a collect into HashMap with put, accepts nulls
Map<String, String> emails = users.stream()
.collect(HashMap::new, (m, u) -> m.put(u.id(), u.email()), HashMap::putAll);
System.out.println("with nulls kept: " + emails);
// When several items share a key and you want ALL of them, group instead
List<String> words = List.of("ant", "bee", "asp", "bat", "cow");
Map<Character, List<String>> byFirst = words.stream()
.collect(Collectors.groupingBy(w -> w.charAt(0)));
System.out.println("groupingBy: " + byFirst);
// Unmodifiable result (Java 10+)
Map<String, Integer> lengths = words.stream()
.collect(Collectors.toUnmodifiableMap(w -> w, String::length));
System.out.println("unmodifiable size: " + lengths.size());
}
}
Output:
toMap with null value: NullPointerException
with nulls kept: {u1=a@x.io, u2=null}
groupingBy: {a=[ant, asp], b=[bee, bat], c=[cow]}
unmodifiable size: 5
throwstoMap for a null value, even thoughNullPointerException allows null values, because it usesHashMap internally, which treats null as "remove". A loop, or the three-argumentMap.merge withcollect , keeps the null.HashMap::put- When several elements share a key and all of them matter,
collects them into a list per key instead of merging. ThegroupingBygroupingBy page covers its downstream collectors. returns a map that rejects changes. It also rejects null keys and values, and duplicate keys unless a merge function is given.toUnmodifiableMap
Index maps, positions and partitions
Sometimes the key is the position in the list, or the map has a fixed set of keys. The name list includes names of two lengths so that partitioning and counting have something to separate.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class IndexAndPartition {
public static void main(String[] args) {
List<String> names = List.of("ann", "bob", "cy", "dee", "ed");
// Position -> element: stream the indexes, not the elements
Map<Integer, String> byIndex = IntStream.range(0, names.size()).boxed()
.collect(Collectors.toMap(Function.identity(), names::get));
System.out.println("by index: " + byIndex);
// Element -> position (first occurrence wins)
Map<String, Integer> positions = IntStream.range(0, names.size()).boxed()
.collect(Collectors.toMap(names::get, i -> i, (first, later) -> first));
System.out.println("position of dee: " + positions.get("dee"));
// partitioningBy: always exactly two keys, true and false
Map<Boolean, List<String>> shortOrLong = names.stream()
.collect(Collectors.partitioningBy(n -> n.length() <= 2));
System.out.println("partitioningBy: " + shortOrLong);
Map<Boolean, List<String>> none = names.stream()
.collect(Collectors.partitioningBy(n -> n.length() > 10));
System.out.println("no matches: " + none);
// groupingBy with a downstream collector: counts and joined values
Map<Integer, Long> countByLength = names.stream()
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
System.out.println("count by length: " + countByLength);
}
}
Output:
by index: {0=ann, 1=bob, 2=cy, 3=dee, 4=ed}
position of dee: 3
partitioningBy: {false=[ann, bob, dee], true=[cy, ed]}
no matches: {false=[ann, bob, cy, dee, ed], true=[]}
count by length: {2=2, 3=3}
- Streams of elements do not know their index, so the program streams the indexes with
and looks up each element withIntStream.range . On anames::get that lookup would be slow; collect to anLinkedList first.ArrayList - Mapping element to position needs a merge function if the list may contain duplicates;
keeps the first position, as(first, later) -> first would.indexOf always returns both keys, even when one side is empty, as the second partition shows. WithpartitioningBy on a boolean condition, a missing side would simply not be in the map.groupingBy withgroupingBy andcounting() gives a sorted count per key: two names of length 2 and three of length 3.TreeMap::new
Composite keys and nested maps
Real data is often keyed by two fields at once, such as region and product. The sales list has two entries for the same pair, so each approach must also combine values.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class CompositeKeys {
record Sale(String region, String product, int units) {
}
// A record makes a correct composite key: equals and hashCode cover both fields
record RegionProduct(String region, String product) {
}
public static void main(String[] args) {
List<Sale> sales = List.of(new Sale("north", "pen", 5), new Sale("south", "pen", 2),
new Sale("north", "ink", 7), new Sale("north", "pen", 3));
Map<RegionProduct, Integer> byPair = sales.stream().collect(Collectors.toMap(
s -> new RegionProduct(s.region(), s.product()), Sale::units, Integer::sum));
System.out.println("record key: " + byPair.get(new RegionProduct("north", "pen")));
// A string key works too, but separators can collide: "a|b" + "c" vs "a" + "b|c"
Map<String, Integer> byText = sales.stream().collect(Collectors.toMap(
s -> s.region() + "|" + s.product(), Sale::units, Integer::sum));
System.out.println("string key: " + byText.get("north|pen"));
// Nested maps: region -> product -> total units
Map<String, Map<String, Integer>> nested = sales.stream().collect(Collectors.groupingBy(
Sale::region, TreeMap::new,
Collectors.groupingBy(Sale::product, TreeMap::new,
Collectors.summingInt(Sale::units))));
System.out.println("nested: " + nested);
System.out.println("north ink: " + nested.get("north").get("ink"));
}
}
Output:
record key: 8
string key: 8
nested: {north={ink=7, pen=8}, south={pen=2}}
north ink: 7
- A record is the cleanest composite key: its generated
andequals use both fields, sohashCode finds the combined total of 8.new RegionProduct("north", "pen") - A concatenated string key also works, but only if the separator can never appear in the data; otherwise two different pairs can produce the same string. It also makes the key's structure invisible to the type system.
- Nested
calls build a map of maps, region first and product second, withgroupingBy totalling the units. Nested maps suit reports and lookups by the first key; a record key suits lookups by the full pair.summingInt - Keys must not change after insertion. A mutable object used as a key, then modified, can no longer be found; see
HashMap internals .
Sizing the map, and how fast each approach is
A HashMap
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class SizingAndSpeed {
record User(String id, int age) {
}
public static void main(String[] args) {
int n = 1000000;
List<User> users = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
users.add(new User("u" + i, i % 90));
}
System.out.printf("%,d users into a Map<String, User>%n", n);
time("loop, new HashMap<>()", () -> {
Map<String, User> m = new HashMap<>();
for (User u : users) {
m.put(u.id(), u);
}
return m;
});
time("loop, new HashMap<>(n) (too small)", () -> {
Map<String, User> m = new HashMap<>(n);
for (User u : users) {
m.put(u.id(), u);
}
return m;
});
time("loop, HashMap.newHashMap(n)", () -> {
Map<String, User> m = HashMap.newHashMap(n);
for (User u : users) {
m.put(u.id(), u);
}
return m;
});
time("stream toMap", () -> users.stream()
.collect(Collectors.toMap(User::id, Function.identity())));
time("parallel stream toMap", () -> users.parallelStream()
.collect(Collectors.toMap(User::id, Function.identity())));
}
// Best of 3 runs
static void time(String name, Supplier<Map<String, User>> build) {
long best = Long.MAX_VALUE;
int size = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
size = build.get().size();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-36s %6.1f ms (%,d entries)%n", name, best / 1e6, size);
}
}
Output (one 2-CPU Linux machine, JDK 21; the times are rough):
1,000,000 users into a Map<String, User>
loop, new HashMap<>() 82.5 ms (1,000,000 entries)
loop, new HashMap<>(n) (too small) 77.7 ms (1,000,000 entries)
loop, HashMap.newHashMap(n) 29.1 ms (1,000,000 entries)
stream toMap 54.5 ms (1,000,000 entries)
parallel stream toMap 132.6 ms (1,000,000 entries)
- A default
starts with 16 buckets and resized about 17 times on the way to a million entries, which made it the slowest loop.HashMap looks presized, but the argument is the table capacity, not the number of entries. With the default load factor of 0.75, the map still resizes once it holds 750,000 entries.new HashMap<>(n) , added in Java 19, sizes the table for n entries, and was the fastest.HashMap.newHashMap(n) andLinkedHashMap.newLinkedHashMap exist for the same reason.HashSet.newHashSet cannot know the final size either, so it also resizes; it landed between the unsized and the presized loops.Collectors.toMap- The parallel stream was the slowest: each thread builds its own map and then all of them are merged, which costs more than it saves on two CPUs.
Why resizing costs what it does is explained on the
Loops with put, putIfAbsent, merge and computeIfAbsent
A loop gives the most control over repeated keys, but only if you pick the right MapannbobtoMap
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class LoopVariants {
record Login(String user, String device) {
}
public static void main(String[] args) {
List<Login> logins = List.of(new Login("ann", "phone"), new Login("bob", "laptop"),
new Login("ann", "tablet"), new Login("bob", "laptop"), new Login("cy", "phone"));
// Four map methods, four rules for a repeated key
Map<String, String> put = new LinkedHashMap<>();
Map<String, String> putIfAbsent = new LinkedHashMap<>();
Map<String, Integer> merge = new LinkedHashMap<>();
Map<String, List<String>> compute = new LinkedHashMap<>();
for (Login l : logins) {
put.put(l.user(), l.device()); // last one wins, silently
putIfAbsent.putIfAbsent(l.user(), l.device()); // first one wins
merge.merge(l.user(), 1, Integer::sum); // combine
compute.computeIfAbsent(l.user(), k -> new ArrayList<>()).add(l.device()); // keep all
}
System.out.println("put: " + put);
System.out.println("putIfAbsent: " + putIfAbsent);
System.out.println("merge(1, sum): " + merge);
System.out.println("computeIfAbsent: " + compute);
// null values: toMap refuses them, a three-argument collect does not
List<String> names = java.util.Arrays.asList("ann", "bob", "cy");
Map<String, String> emails = new HashMap<>(Map.of("ann", "ann@x.io", "cy", "cy@x.io"));
Map<String, String> withNulls = names.stream().collect(HashMap::new,
(m, n) -> m.put(n, emails.get(n)), Map::putAll);
System.out.println("collect with null value: " + new TreeMap<>(withNulls));
// Keys that differ only in case or spaces become one key after normalising
List<String> tags = List.of("Java", "java ", "JAVA", "Kotlin");
Map<String, Long> raw = tags.stream()
.collect(Collectors.groupingBy(t -> t, TreeMap::new, Collectors.counting()));
Map<String, Long> normal = tags.stream().collect(Collectors.groupingBy(
t -> t.strip().toLowerCase(Locale.ROOT), TreeMap::new, Collectors.counting()));
System.out.println("raw keys: " + raw.size() + " " + raw.keySet()
+ ", normalised: " + normal);
}
}
put: {ann=tablet, bob=laptop, cy=phone}
putIfAbsent: {ann=phone, bob=laptop, cy=phone}
merge(1, sum): {ann=2, bob=2, cy=1}
computeIfAbsent: {ann=[phone, tablet], bob=[laptop, laptop], cy=[phone]}
collect with null value: {ann=ann@x.io, bob=null, cy=cy@x.io}
raw keys: 4 [JAVA, Java, Kotlin, java ], normalised: {java=3, kotlin=1}
kept the last device,put , and threw nothing. Unlikeann=tablet without a merge function, a loop withtoMap loses duplicates silently, so use it only when the last value is truly the one you want.put (Java 8) kept the first device,putIfAbsent , the same result asann=phone withtoMap .(a, b) -> a counted logins per user, 2 formerge(user, 1, Integer::sum) andann . It is the loop form ofbob withgroupingBy .counting() kept every device, including bothcomputeIfAbsent(user, k -> new ArrayList<>()).add(device) logins forlaptop . The lambda runs only for a new key, so only one list is created per user.bob- The three-argument
calledcollect directly and storedHashMap.put , whichbob=null would have rejected withtoMap . Its combiner,NullPointerException , also makes the last value win on duplicate keys.Map::putAll - The tags
,Java andjava produced 4 separate keys. Normalising the key withJAVA andstrip() merged them intotoLowerCase(Locale.ROOT) . A fixed locale matters here: in a Turkish locale,java=3 produces a dotless"TITLE".toLowerCase() , so the same input would give different keys on different machines.ı
Which approach to use
| Situation | Use |
|---|---|
| Keys are unique, such as IDs | toMap(Item::id, Function.identity()) |
| Keys may repeat; combine values | toMap(key, value, Integer::sum) |
| Keys may repeat; keep the first | toMap(key, value, (a, b) -> a) |
| Keys may repeat; keep all elements | groupingBy(key) |
| Keep the list's order | Add LinkedHashMap::new |
| Sorted keys | Add TreeMap::new |
| Values may be null | A loop, or collect(HashMap::new, ...) |
| Split by a condition | partitioningBy |
| Large list, known size | A loop into HashMap.newHashMap(n) |
| Read-only result | toUnmodifiableMap |