Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collecting lists from an object list using Java 8 Stream API

Tags:

I have a class like this

public class Example {     private List<Integer> ids;      public getIds() {         return this.ids;      } } 

If I have a list of objects of this class like this

List<Example> examples; 

How would I be able to map the id lists of all examples into one list? I tried like this:

List<Integer> concat = examples.stream().map(Example::getIds).collect(Collectors.toList()); 

but getting an error with Collectors.toList()

What would be the correct way to achive this with Java 8 stream api?

like image 630
Jakob Abfalter Avatar asked Apr 28 '17 14:04

Jakob Abfalter


People also ask

How do you convert a List of objects into a stream of objects?

Converting a list to stream is very simple. As List extends the Collection interface, we can use the Collection. stream() method that returns a sequential stream of elements in the list.

How do you filter a List of objects using a stream?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.

How do I get a List of fields from a List of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.


2 Answers

Use flatMap:

List<Integer> concat = examples.stream()     .flatMap(e -> e.getIds().stream())     .collect(Collectors.toList()); 
like image 115
Andy Turner Avatar answered Oct 08 '22 23:10

Andy Turner


Another solution by using method reference expression instead of lambda expression:

List<Integer> concat = examples.stream()                                .map(Example::getIds)                                .flatMap(List::stream)                                .collect(Collectors.toList()); 
like image 24
holi-java Avatar answered Oct 09 '22 00:10

holi-java