I just started with Java 8 and streams, and not able to find out how to write this code in Java 8:
Map<Integer, CarShop> result = new HashMap<>();
for (Car car : someListOfCars) {
List<CarProduct> listOfCarProducts = car.getCarProducts();
for (CarProduct product : listOfCarProducts) {
result.put(product.getId(), car.getCarShop());
}
}
Any help?
You can often convert your iterative solution directly to a stream by using
.collect
:You can make the solution more flexible at the cost of additional allocations:
This will allow you to collect any way you wish. For example, you would be able to remove
(a,b)->b
to force an exception if there are duplicate ids instead of silently overwriting the entry.