How to use stream in Java 8 to collect a couple of fields into one list?

user2620644 :

For example I have class Person with name and surname fields.

I want to collect a List of String (names and surnames all together) from List of Person, but it seems that I can't use map twice per one list or can't use stream twice per list.

My code is:

persons.stream()
   .map(Person::getName)
   .collect(Collectors.toSet())
   .stream().map(Person::getSurname) 
   .collect(Collectors.toList())

but it keeps telling me that Person::getSurname non-static method can't be referenced from static context.

What am I doing wrong?

Landei :

To get both names and surnames in the same list, you could do this:

List<String> set = persons.stream()
  .flatMap(p -> Stream.of(p.getName(),p.getSurname()))
  .collect(Collectors.toList());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=451688&siteId=1
Recommended