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

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: HashMap has no order, LinkedHashMap keeps insertion order, and TreeMap sorts the keys.

Ways to build a map from a list
ApproachSinceDuplicate keysBest for
for loop with putJava 1.2Last value wins silentlySimple code, nulls, custom rules
Collectors.toMap(key, value)Java 8Throws IllegalStateExceptionKeys known to be unique
toMap(key, value, merge)Java 8The merge function decidesSumming, keeping first or last
toMap(key, value, merge, mapFactory)Java 8The merge function decidesA specific map type
Collectors.groupingByJava 8Collected into a list or other resultKeeping all elements per key
Collectors.partitioningByJava 8Two keys only: true and falseSplitting by a condition
Collectors.toUnmodifiableMapJava 10ThrowsRead-only results

The examples ran on JDK 21. For the reverse direction, see converting a map to a list.

The basic conversion: toMap and a loop

Three products with unique SKUs are the simple case, where every approach gives the same map.

Java
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:

Output
B7 -> Mouse
Monitor costs 189.0
loop map has 3 entries
  • toMap(Product::sku, Function.identity()) maps each SKU to its product, the usual way to build a lookup table by ID.
  • toMap(Product::name, Product::price) keeps only one property as the value.
  • 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 fails. The program tries it, then fixes it with merge functions and picks the map type.

Java
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:

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 zoe threw IllegalStateException. Since Java 9 the message names the key and both values, which makes the bad data easy to find. A loop with put would instead have kept 20 and silently dropped 30.
  • Integer::sum as the merge function adds the amounts, giving 50 for zoe; (a, b) -> a keeps the first value seen.
  • The default result is a HashMap, whose order depends on hash codes. The fourth argument, LinkedHashMap::new or TreeMap::new, gives insertion order or sorted keys. The map type can only be chosen together with a merge function.

Null values and grouping

A user without an email has a null value, and several words share a first letter, so this program covers the two other common surprises.

Java
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:

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
  • toMap throws NullPointerException for a null value, even though HashMap allows null values, because it uses Map.merge internally, which treats null as "remove". A loop, or the three-argument collect with HashMap::put, keeps the null.
  • When several elements share a key and all of them matter, groupingBy collects them into a list per key instead of merging. The groupingBy page covers its downstream collectors.
  • toUnmodifiableMap returns a map that rejects changes. It also rejects null keys and values, and duplicate keys unless a merge function is given.

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.

Java
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:

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 IntStream.range and looks up each element with names::get. On a LinkedList that lookup would be slow; collect to an ArrayList first.
  • Mapping element to position needs a merge function if the list may contain duplicates; (first, later) -> first keeps the first position, as indexOf would.
  • partitioningBy always returns both keys, even when one side is empty, as the second partition shows. With groupingBy on a boolean condition, a missing side would simply not be in the map.
  • groupingBy with counting() and TreeMap::new gives a sorted count per key: two names of length 2 and three of length 3.

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.

Java
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:

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 equals and hashCode use both fields, so new RegionProduct("north", "pen") finds the combined total of 8.
  • 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 groupingBy calls build a map of maps, region first and product second, with summingInt totalling the units. Nested maps suit reports and lookups by the first key; a record key suits lookups by the full pair.
  • 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 grows by doubling its table and rehashing every entry, so its initial size affects speed for large lists. The program builds a map of a million users five ways, keeping the fastest of three runs.

Java
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):

Output
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 HashMap starts with 16 buckets and resized about 17 times on the way to a million entries, which made it the slowest loop.
  • new HashMap<>(n) 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.
  • HashMap.newHashMap(n), added in Java 19, sizes the table for n entries, and was the fastest. LinkedHashMap.newLinkedHashMap and HashSet.newHashSet exist for the same reason.
  • Collectors.toMap cannot know the final size either, so it also resizes; it landed between the unsized and the presized loops.
  • 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 HashMap internals page.

Loops with put, putIfAbsent, merge and computeIfAbsent

A loop gives the most control over repeated keys, but only if you pick the right Map method. The four methods below differ exactly in what they do when the key is already there. The program feeds the same five logins, with ann and bob appearing twice, to each of them, and then handles two cases that toMap gets wrong.

Java
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);
    }
}
Output
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}
  • put kept the last device, ann=tablet, and threw nothing. Unlike toMap without a merge function, a loop with put loses duplicates silently, so use it only when the last value is truly the one you want.
  • putIfAbsent (Java 8) kept the first device, ann=phone, the same result as toMap with (a, b) -> a.
  • merge(user, 1, Integer::sum) counted logins per user, 2 for ann and bob. It is the loop form of groupingBy with counting().
  • computeIfAbsent(user, k -> new ArrayList<>()).add(device) kept every device, including both laptop logins for bob. The lambda runs only for a new key, so only one list is created per user.
  • The three-argument collect called HashMap.put directly and stored bob=null, which toMap would have rejected with NullPointerException. Its combiner, Map::putAll, also makes the last value win on duplicate keys.
  • The tags Java, java and JAVA produced 4 separate keys. Normalising the key with strip() and toLowerCase(Locale.ROOT) merged them into java=3. A fixed locale matters here: in a Turkish locale, "TITLE".toLowerCase() produces a dotless ı, so the same input would give different keys on different machines.

Which approach to use

Choosing a list-to-map conversion
SituationUse
Keys are unique, such as IDstoMap(Item::id, Function.identity())
Keys may repeat; combine valuestoMap(key, value, Integer::sum)
Keys may repeat; keep the firsttoMap(key, value, (a, b) -> a)
Keys may repeat; keep all elementsgroupingBy(key)
Keep the list's orderAdd LinkedHashMap::new as the fourth argument
Sorted keysAdd TreeMap::new
Values may be nullA loop, or collect(HashMap::new, ...)
Split by a conditionpartitioningBy
Large list, known sizeA loop into HashMap.newHashMap(n)
Read-only resulttoUnmodifiableMap