0

Am trying to iterate an ArrayList using Java 8 - Lambda forEach and to store the value in the global variable.

Am getting the error like type mis-match and am not able to typecast also.

Please see my code below.

Long product_id = listProducts.forEach(listproducts ->listproducts.getId());

My Previous approach : (without JAVA8 feature, now i want to change my code by using Java8)

 for(Product prod : listProducts)
        {
            product_id=prod.getId();
        }
5
  • 2
    forEach doesn't return anything. What exactly do you expect the output to be. You are processing a list of elements and seem to require a single value as the output. Commented Jan 9, 2018 at 10:08
  • Yes., it want to get a single value out of the list. previously i was using old method. But, just want to convert my code with new Java8 feactures. I will update my old code too. Commented Jan 9, 2018 at 10:13
  • 5
    Why do you use a loop in your original code? All but the final value assigned to product_id will be overwritten. Commented Jan 9, 2018 at 10:15
  • 2
    you may use like Long product_id = listProducts.get(listProducts.size()-1).getId(); no need any loop for this purpose. Commented Jan 9, 2018 at 10:29
  • You should fix the logic errors of your code first, then you may think about expressing the actual intent using a different API. Commented Jan 9, 2018 at 12:10

2 Answers 2

1
final Long prod[] = new Long[1];
listProducts.forEach(product->{         
    prod[0] = product.getId();      
});

Long product_id = prod[0];
Sign up to request clarification or add additional context in comments.

Comments

1

sYou can not extract one single value from a list of values without aggregating it (max, min, sum, ...). In your old code you always saved the last id of your list of products. Is this intended? If so a loop does not make any sense. You can just retrieve the last element:

Long product_id = listProducts.get(listProducts.size() - 1);

But if you want to map the products to a list of their ids you can do something like:

List<Long> productIds = listProducts.stream().map(prod -> prod.getId()).collect(Collectors.toList());

UPDATE:
Or to get a single ID (if list is empty, the productId is null):

Long productId = listProducts.stream().map(prod -> prod.getId()).reduce((id1, id2) -> id2).orElse(null);

Comments

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.