Missing return statement in Java stream

Viewed 224

I have the following list and map:

final List<Product> productList = productService.findAll(uuidList);

Map<UUID, Product> productMap = new HashMap<>();

I want to add the element pairs to the map as shown below:

productList.stream().map(product -> {
    productMap.put(product.getUuid(), product);
});

However, the last line throws "Missing return statement" error. When I update as shown below, it has gone, but this time return is useless. So, how should I add UUID and Product pair to my map?

1 Answers

No need to use map here, you can simply use forEach. The map method is intended to create another stream whose elements are "mapped" from the original stream.forEach just applies a consumer on each element, in this case the consumer is putting the element into a hash map.

productList.stream().forEach(product -> 
    productMap.put(product.getUuid(), product)
);

You can also simplify the code by using a map collector:

Map<UUID, Product> productMap = productList.stream()
                                           .collect(Collectors.toMap(Product::getUuid, Function.identity()));

As for the reason why the original code with map is not compiling, it's because the map method expects a Function which by definition takes a value and returns something. Since you're using curly brackets, you should add a return statement. Alternatively you can remove the brackets, but keep in mind what I mentioned above, and that the return value is meaningless in this case since it's not used:

productList.stream().map(product -> 
    productMap.put(product.getUuid(), product);
);
Related