Video in progress

Strong Junior 🌊 Streams and lambdas

What happens when you use Collectors.toMap() and the same key comes twice?

You get IllegalStateException: Duplicate key. To prevent that, you pass a third argument, a merge function, which decides which of the two values to keep (or how to combine them).

📖 Answer

record Product(String sku, String name, int price) {}

Map<String, Product> bySku = products.stream()
        .collect(Collectors.toMap(Product::sku, p -> p));
// if two products have the same sku: IllegalStateException

Everything works with test data, and it fails in prod as soon as a duplicate appears in the database. This is the classic case.

With a merge function:

// keep the last one
Collectors.toMap(Product::sku, p -> p, (old, neu) -> neu)

// keep the cheaper one
Collectors.toMap(Product::sku, p -> p,
        (a, b) -> a.price() <= b.price() ? a : b)

// add up the amounts
Collectors.toMap(Order::customerId, Order::amount, Long::sum)

Two more things:

  • if a value is null you also get an NPE: toMap checks the value for null (the variant with a merge function uses HashMap.merge, which doesn't accept null either);
  • if you need order, the fourth argument: LinkedHashMap::new.

Even if you're sure there can't be duplicates, leaving out the merge function is a decision of "if there are any, I want to know". Sometimes that's right, just make it a conscious choice.