Java 8 foreach add subobject to new list

Valentin Grégoire :

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.

Bohemian :

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());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452437&siteId=1