19

Is it possible in Java 8 to write something like this:

List<A> aList = getAList();
List<B> bList = new ArrayList<>();

for(A a : aList) {
    bList.add(a.getB());
}

I think it should be a mix of following things:

aList.forEach((b -> a.getB());

or

aList.forEach(bList::add);

But I can't mix these two to obtain the desired output.

0

1 Answer 1

46

Here are a few ways

aList.stream().map(A::getB).forEach(bList::add);
// or
aList.forEach(a -> bList.add(a.getB()));

or you can even create bList() on the fly:

List<B> bList = aList.stream().map(A::getB).collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

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.