Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 streaming: How to convert list of objects to a list of its selected properties

I have a class

class Person {
   // get/set omitted for simplicity
   public String firstName;
   public String lastName;
}

also I have a list of such objects

List<Person> list ...

I need to convert with the streams the following

List<Person> list ...
List<String> firstLastNames = list.stream()....

So my List firstLastNames will contain first and last names in this list. So.

System.out.println(firstLastNames); // will give me -> "John", "Smith", "Jessica", "Jones".. etc.
like image 523
walv Avatar asked Dec 11 '22 10:12

walv


1 Answers

How about something like this

stream.stream().flatMap(p -> Stream.of(p.firstName, p.lastName)).collect(Collectors.toList());
like image 176
Tomek Avatar answered May 12 '23 00:05

Tomek