Skip to content

Commit 3f8756a

Browse files
committed
One more (crazy) solution.
1 parent 4f72662 commit 3f8756a

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

‎src/main/java/de/codecentric/java8examples/streaming/CollectingAndReducing.java‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,25 @@ public static Map<String, String> cheapestDealersByProduct(List<Invoice> invoice
120120
* From a given list of invoices, compute for every dealer the available products together with its price.
121121
*/
122122
public static Map<String, List<ProductWithPrice>> computeDealerInventory(List<Invoice> invoices) {
123-
return Collections.emptyMap();
123+
Function<SimpleEntry<String, ProductWithPrice>, String> classifier =
124+
(SimpleEntry<String, ProductWithPrice> entry) -> (String) entry.getKey();
125+
Function<SimpleEntry<String, ProductWithPrice>, ProductWithPrice> mapper =
126+
(SimpleEntry<String, ProductWithPrice> entry) -> (ProductWithPrice) entry.getValue();
127+
128+
Map<String, List<Invoice>> invoicesBySender = invoices.stream()
129+
.collect(Collectors.groupingBy(Invoice::getSender));
130+
return invoicesBySender.entrySet().stream()
131+
.<SimpleEntry<String, ProductWithPrice>>flatMap(entry -> entry.getValue().stream()
132+
.flatMap((Invoice invoice) -> invoice.getItems().stream())
133+
.map((InvoiceItem item) -> new SimpleEntry<String, ProductWithPrice>(
134+
entry.getKey(),
135+
new ProductWithPrice(item.getProduct(), item.getPricePerUnit()))))
136+
.distinct()
137+
.collect(Collectors.groupingBy(
138+
classifier,
139+
Collectors.mapping(
140+
mapper,
141+
Collectors.toList())));
124142
}
125143

126144
/**

0 commit comments

Comments
 (0)