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?
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.
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.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
Use flatMap
:
List<Integer> concat = examples.stream() .flatMap(e -> e.getIds().stream()) .collect(Collectors.toList());
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());
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