Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 foreach add subobject to new list

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.

like image 429
Valentin Grégoire Avatar asked Sep 05 '16 08:09

Valentin Grégoire


People also ask

Can forEach return a value in Java?

Return Values of ArrayList forEach() in JavaforEach() method does not return any value.

How do you add to an existing List in Java?

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.

Why forEach method is added to each collection?

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.


1 Answers

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());
like image 89
Bohemian Avatar answered Oct 13 '22 14:10

Bohemian