0

I am trying to convert below for-loop to forEach method with help Stream function using Java1.8, but I was messed up and also confused to do that.

List<A> valueList = new ArrayList<>();
List<B> responseList = getResponses();
List<A> value = new ArrayList<>();

for (B getResponse: responseList) {
    valueList = getValues(getResponse);
    value.addAll(valueList);
}
0

3 Answers 3

5

With streams you generally want to avoid creating empty lists and then adding items. Streams should use functional idioms and avoid side effects as much as possible. It's better to work with the stream as a whole and then "collect" the results into a list at the end.

List<C> value = getResponses().stream()
    .flatMap(r -> getValues(r).stream())
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

2

I am trying to convert below for-loop to forEach method with help Stream function using Java 1.8.

You shouldn't use a stream along with forEach simply to accumulate into a predefined list as there will be side effects (which should be avoided when dealing with streams), rather go with the stream approach suggested by John Kugelman if you want to perform it with streams or using the forEach method it can also be done as:

List<A> value = new ArrayList<>();
responseList.forEach(response -> value.addAll(getValues(response))));

Comments

-1

It appears you are trying to add all the values in responseList to valueList and I think you could just do valueList.addAll(responseList); and not have to use a for loop at all.

You could have a problem though if type B doesn't inherit from A because you can't have a list of two unrelated types.

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.