6

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?

4
  • 3
    Can we see what have you tried and where tricky part starts? Commented Jun 12, 2015 at 21:19
  • 2
    Also how does your Car CarProduct and CarShop classes looks like (car.getCarProducts() doesn't feel very intuitive to me)? Commented Jun 12, 2015 at 21:21
  • The cars, and carshop is just fictional. Nevermind the domain. I've tried with different variations of flatmap and collectors, and map reduce, but I just can't make it work right... Commented Jun 12, 2015 at 21:24
  • 3
    I am not saying your question is very bad, but don't you think it would help answering it if we would have ready code to test our answers? Generally you should expect same amount of effort form answerer as you put in asking question. Commented Jun 12, 2015 at 21:34

1 Answer 1

10

You can often convert your iterative solution directly to a stream by using .collect:

Map<Integer, CarShop> result = someListOfCars.stream().collect(
        HashMap::new,
        (map, car) -> car.getCarProducts().forEach(
                prod -> map.put(prod.getId(), car.getCarShop())
        ),
        Map::putAll
);

You can make the solution more flexible at the cost of additional allocations:

Map<Integer, CarShop> result = someListOfCars.stream()
        .flatMap(car -> car.getCarProducts().stream()
                .map(prod -> new SimpleImmutableEntry<>(prod.getId(), car.getCarShop()))
        ).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works and makes things a bit more clear. I did try something like this, but I guess I don't fully understand how these functional interfaces works yet..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.