How to use stream in Java 8 to collect a couple of fields into one list?
Your code should look something like that:
persons.stream()
.map(person -> person.getName() + " " + person.getSurname)
.collect(Collectors.toList());
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());
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.