Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Using Guava, group a list of Order(customerId, amount) into a Multimap of customer id to orders, then print each customer's total. How would you do the same with only the JDK?

With Guava, Multimaps.index(orders, Order::customerId) groups the orders into an ImmutableListMultimap from customer id to that customer's orders, and byCustomer.asMap().forEach(...) lets us sum each list with BigDecimal::add. With only the JDK, orders.stream().collect(Collectors.groupingBy(Order::customerId, Collectors.reducing(BigDecimal.ZERO, Order::amount, BigDecimal::add))) gives the totals directly. The Multimap saves us the manual computeIfAbsent(key, k -> new ArrayList<>()).add(v) pattern, and Multimaps.index rejects null keys and values, which surfaces data problems early.

Why this question is asked

Grouping records by a key and totalling each group is one of the most common jobs in business code: orders per customer, payments per invoice, events per user. Interviewers ask this small coding question because it shows whether we know the collection types and collectors available to us, and whether we pay attention to details such as money types, ordering and nulls. In this answer, we will recap what a multimap is, write the Guava version, compute the totals, write the same thing with only the JDK, compare it with the manual map-of-lists pattern, and look at how nulls are handled.

1A Quick Recap of Multimaps

A normal Map holds one value per key. When we need many values per key, the usual workaround is a Map<String, List<Order>>, which works but makes us create the inner list for each new key and check for missing keys when reading. A Multimap is a collection designed for this: put(key, value) adds another value under the key, and get(key) returns all values for the key, or an empty collection, never null.

Guava has several kinds. A ListMultimap keeps the values for each key as a list, in insertion order and allowing duplicates, which is what we want for orders. A SetMultimap keeps a set, removing duplicates. Each comes in mutable and immutable variants.

2Grouping the Orders With Multimaps.index

Multimaps.index takes a collection and a function that computes the key of each element, and returns an ImmutableListMultimap. It is a one-line grouping for the common case where the key comes from the value itself.

Java
record Order(String customerId, BigDecimal amount) {}
List<Order> orders = List.of(
new Order("c1", new BigDecimal("10.00")),
new Order("c2", new BigDecimal("5.50")),
new Order("c1", new BigDecimal("2.25")));
ImmutableListMultimap<String, Order> byCustomer = Multimaps.index(orders, Order::customerId);
byCustomer.get("c1"); // [Order[customerId=c1, amount=10.00], Order[customerId=c1, amount=2.25]]
byCustomer.get("c3"); // []: no null checks needed
byCustomer.keySet(); // [c1, c2]: first-seen order
byCustomer.size(); // 3: counts values, not keys

Notice two details. size() counts all key-value pairs, three orders, not two customers; keySet().size() gives the number of customers. And the immutable multimap keeps keys in the order they were first seen, so our output will be stable from run to run.

3Printing Each Customer's Total

asMap() gives a view of the multimap as a Map<String, Collection<Order>>, which is exactly what we need to work per customer. For each customer we map the orders to their amounts and reduce them with BigDecimal::add, starting from BigDecimal.ZERO.

Java
byCustomer.asMap().forEach((customerId, customerOrders) -> {
BigDecimal total = customerOrders.stream()
.map(Order::amount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(customerId + " " + total);
});
// c1 12.25
// c2 5.50
Step throughFrom a list of orders to totals
orders listMultimaps.indexListMultimapTotals
c1 10.00, c2 5.50, c1 2.25
key = order.customerId()
c1 -> [10.00, 2.25], c2 -> [5.50]
asMap(): reduce each list with BigDecimal::add
c1 12.25, c2 5.50

5 messages in order. Play them, or step through them one at a time.

We use BigDecimal rather than double because money must add up exactly. With doubles, 0.1 + 0.2 is 0.30000000000000004, and over thousands of orders such errors become visible differences in reports. BigDecimal.add keeps the scale, so 10.00 + 2.25 prints as 12.25.

4Doing the Same With Only the JDK

The JDK's streams can do the grouping and the total in one collector. Collectors.groupingBy takes the key function and a downstream collector that decides what to do with each group. Collectors.reducing(identity, mapper, operator) turns each group into a single value.

Java
Map<String, BigDecimal> totals = orders.stream()
.collect(Collectors.groupingBy(
Order::customerId,
LinkedHashMap::new, // keep first-seen order
Collectors.reducing(BigDecimal.ZERO, Order::amount, BigDecimal::add)));
totals.forEach((id, total) -> System.out.println(id + " " + total));
// c1 12.25
// c2 5.50
// Just the groups, like the Multimap:
Map<String, List<Order>> groups = orders.stream().collect(Collectors.groupingBy(Order::customerId));

Notice the LinkedHashMap::new argument. The two-argument groupingBy returns a HashMap, whose iteration order is not defined, so the printed order could differ from the Guava version. Passing a map factory makes the order explicit: LinkedHashMap for first-seen order, TreeMap::new for sorted ids. If we only need the totals, the JDK version is arguably simpler, because it never builds the lists of orders at all.

5What the Multimap Saves Us From

Before streams and multimaps, and still in a lot of code, grouping looked like this. It is correct, but it is the kind of code that gets copied with small mistakes.

Java
Map<String, List<Order>> groups = new HashMap<>();
for (Order o : orders) {
groups.computeIfAbsent(o.customerId(), k -> new ArrayList<>()).add(o);
}
groups.get("c3"); // null: every reader must remember to check

The Multimap removes the inner-list management, never returns null from get, and makes the intent, many orders per customer, visible in the type. When a grouping is used in several places, passed around and queried, a Multimap is clearer. When it is a one-off calculation, a collector is enough.

6How Nulls Are Handled

Multimaps.index throws NullPointerException if any order is null or if the key function returns null for an order, that is, an order with no customer id. That can feel strict, but it surfaces a data problem at the point of grouping, instead of producing a mysterious null customer in a report. The JDK is strict too: groupingBy throws NullPointerException with the message element cannot be mapped to a null key, and BigDecimal::add fails on a null amount in either version.

So if null customer ids are possible, we decide explicitly what they mean, for example filtering them out with a warning or mapping them to an UNKNOWN key, before grouping.

7Follow-up questions

How would you get the customer with the highest total?

From the totals map: totals.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey). BigDecimal is Comparable, so comparingByValue works directly. Note that compareTo ignores scale, so 12.25 and 12.250 compare as equal, which is what we want here.

When would you use a SetMultimap instead?

When duplicates must collapse, for example the set of distinct product categories each customer bought from. For orders, duplicates are real separate orders, so a ListMultimap is right.

Is ImmutableListMultimap safe to share between threads?

Yes. It cannot change after creation, so it can be published and read from many threads without locking, which makes it a good choice for reference data built once at startup.

8Conclusion

In this answer, we grouped orders by customer with Guava's Multimaps.index, which returns an ImmutableListMultimap in first-seen key order, and summed each customer's amounts through asMap() with BigDecimal::add. With only the JDK, groupingBy with a LinkedHashMap factory and Collectors.reducing gives the totals in one collector. We saw that the Multimap removes the computeIfAbsent boilerplate and never returns null, and that both Guava and the JDK reject null keys, so missing customer ids surface early.

What to say in the interviewAbout 70 seconds aloud

Open with

With Guava I'd write Multimaps.index(orders, Order::customerId), which returns an ImmutableListMultimap from customer id to that customer's orders, keeping keys in first-seen order. Then byCustomer.asMap().forEach gives me each customer id with its collection of orders, and I map them to amounts and reduce with BigDecimal.ZERO and BigDecimal::add, printing c1 12.25 and c2 5.50.

Then, if they want more

I use BigDecimal because money has to add up exactly. With only the JDK, I'd stream the orders and collect with groupingBy on customerId, with LinkedHashMap::new as the map factory so the order is predictable, and Collectors.reducing with BigDecimal.ZERO, Order::amount and BigDecimal::add as the downstream collector, which gives the totals directly without building the lists.

The Multimap is nicer when the grouping itself is used in several places: it avoids the manual computeIfAbsent with a new ArrayList pattern, and get never returns null.

One more detail: Multimaps.index rejects null keys and values, and groupingBy also rejects null keys, so an order without a customer id fails fast; if that can happen legitimately, I'd decide explicitly whether to filter it or map it to an unknown key.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using Guava, group a list of Order(customerId, amount) into a Multimap of customer id to...": https://scrivio-interview-library.netlify.app/java/utility-libraries/e39ff2a9c0/