Java 8: Compute revenue per product from orders (flatMap, groupingBy, reduce). Compare loop and stream solutions.
Problem
Each Order has a list of LineItem(productId, quantity, unitPrice). Return total revenue per product and the top 3 products by revenue. Use BigDecimal for money.
import java.math.BigDecimal;
import java.util.List;
final class LineItem {
final String productId;
final int quantity;
final BigDecimal unitPrice;
LineItem(String productId, int quantity, String unitPrice) {
this.productId = productId; this.quantity = quantity; this.unitPrice = new BigDecimal(unitPrice);
}
BigDecimal total() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }
}
final class Order {
final List<LineItem> items;
Order(List<LineItem> items) { this.items = items; }
}Approach 1: Nested loops with a HashMap (Java 7)
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class RevenueLoop {
static Map<String, BigDecimal> perProduct(List<Order> orders) {
Map<String, BigDecimal> revenue = new HashMap<>();
for (Order o : orders) {
for (LineItem li : o.items) {
BigDecimal current = revenue.get(li.productId);
revenue.put(li.productId, current == null ? li.total() : current.add(li.total()));
}
}
return revenue;
}
}Approach 2: Loop with Map.merge (Java 8)
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class RevenueMerge {
static Map<String, BigDecimal> perProduct(List<Order> orders) {
Map<String, BigDecimal> revenue = new HashMap<>();
orders.forEach(o -> o.items.forEach(li -> revenue.merge(li.productId, li.total(), BigDecimal::add)));
return revenue;
}
}Approach 3: Streams: flatMap + groupingBy + reducing
flatMap turns a stream of orders into a stream of line items; reducing sums BigDecimals (there is no summingBigDecimal).
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class RevenueGrouping {
static Map<String, BigDecimal> perProduct(List<Order> orders) {
return orders.stream()
.flatMap(o -> o.items.stream())
.collect(Collectors.groupingBy(li -> li.productId,
Collectors.reducing(BigDecimal.ZERO, LineItem::total, BigDecimal::add)));
}
}Approach 4: Streams: toMap with a merge function
Equivalent and often a little faster, because there is no intermediate downstream collector per key.
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class RevenueToMap {
static Map<String, BigDecimal> perProduct(List<Order> orders) {
return orders.stream()
.flatMap(o -> o.items.stream())
.collect(Collectors.toMap(li -> li.productId, LineItem::total, BigDecimal::add));
}
}Top 3 products: sort everything vs a bounded heap
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.stream.Collectors;
class TopProducts {
// O(p log p): simple and fine for thousands of products
static List<String> bySorting(Map<String, BigDecimal> revenue, int k) {
return revenue.entrySet().stream()
.sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
.limit(k).map(Map.Entry::getKey).collect(Collectors.toList());
}
// O(p log k): keeps only k entries; better for millions of products
static List<String> byHeap(Map<String, BigDecimal> revenue, int k) {
PriorityQueue<Map.Entry<String, BigDecimal>> heap = new PriorityQueue<>(Map.Entry.comparingByValue());
for (Map.Entry<String, BigDecimal> e : revenue.entrySet()) {
heap.offer(e);
if (heap.size() > k) heap.poll();
}
List<String> top = new ArrayList<>();
while (!heap.isEmpty()) top.add(heap.poll().getKey());
Collections.reverse(top);
return top;
}
}
class RevenueDemo {
public static void main(String[] args) {
List<Order> orders = java.util.Arrays.asList(
new Order(java.util.Arrays.asList(new LineItem("pen", 10, "1.50"), new LineItem("book", 2, "12.00"))),
new Order(java.util.Arrays.asList(new LineItem("pen", 4, "1.50"), new LineItem("lamp", 1, "30.00"))),
new Order(java.util.Arrays.asList(new LineItem("book", 1, "12.00"), new LineItem("mug", 3, "4.25"))));
Map<String, BigDecimal> r = new java.util.TreeMap<>(RevenueToMap.perProduct(orders));
System.out.println(r); // {book=36.00, lamp=30.00, mug=12.75, pen=21.00}
System.out.println(r.equals(new java.util.TreeMap<>(RevenueLoop.perProduct(orders)))
&& r.equals(new java.util.TreeMap<>(RevenueMerge.perProduct(orders)))
&& r.equals(new java.util.TreeMap<>(RevenueGrouping.perProduct(orders)))); // true
System.out.println(TopProducts.bySorting(r, 3) + " " + TopProducts.byHeap(r, 3)); // [book, lamp, pen] twice
}
}Feasible → optimal
All aggregation approaches are O(n) over line items. Approach 2 or 4 is the cleanest; Approach 3 shines when you need several aggregates per key (pass a different downstream collector). For top-K, the heap is O(p log k) versus O(p log p) for sorting. For huge datasets, run the same aggregation in the database (GROUP BY) instead of loading every order into memory.
Follow-up questions interviewers ask
Try answering each one before you open it.
Why use BigDecimal and not double for revenue?
Binary floating point cannot represent most decimal fractions exactly, so sums drift (0.1 + 0.2 = 0.30000000000000004) and totals may not match invoices. BigDecimal is exact for decimals. Construct it from a String (new BigDecimal("1.50")), not from a double, and use compareTo rather than equals when scale may differ (2.0 vs 2.00).
When would you push this computation into SQL instead?
Almost always for production reports: SELECT product_id, SUM(quantity * unit_price) FROM line_item GROUP BY product_id ORDER BY 2 DESC LIMIT 3 uses indexes, avoids transferring every row over the network and avoids loading millions of entities into the heap. Use Java streams for in-memory data you already hold, or for logic SQL cannot express.