Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a List from some class properties with Java 8 Stream?

People also ask

How do I print List values in stream?

There are 3 ways to print the elements of a Stream in Java: forEach() println() with collect() peek()

How can we get a stream from a List in Java?

Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.


You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());