Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Missing return statement in Java stream

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading