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.
Return Values of ArrayList forEach() in JavaforEach() method does not return any value.
There are two methods to add elements to the list. add(E e): appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created. add(int index, E element): inserts the element at the given index.
The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With