21

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
user2620644
  • 521
  • 1
  • 12
  • 25

4 Answers4

25

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());
Landei
  • 54,104
  • 13
  • 100
  • 195
7

When you're doing :

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

The result is a Set<String> that contains only the name of the persons. Then you're recreating a stream from this Set and not from your List<Person> persons.

That's why you can not use Person::getSurname to map this Set.

The solution from @Alexis C. : persons.stream().flatMap(p -> Stream.of(p.getName(), p.getSurname()).collect(Collectors.toSet()) must do the job.

Matthieu Saleta
  • 1,388
  • 1
  • 11
  • 17
2

Your code should look something like that:

persons.stream()
.map(person -> person.getName() + " " + person.getSurname)
.collect(Collectors.toList());
matejetz
  • 520
  • 3
  • 7
0

if person has first name and middle name optional then use below code

return Stream.of(Optional.ofNullable(person)
.map(Person::getFirstName)
.orElse(null),
Optional.ofNullable(person)
.map(Person::getMiddleName)
.orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.joining(SPACE));