Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 245
user2620644 Avatar asked Feb 03 '17 15:02

user2620644


People also ask

Can we convert stream to List in Java?

Stream class has toArray() method to convert Stream to Array, but there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion methods between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.

How do you combine streams in Java?

concat() in Java. Stream. concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.


3 Answers

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());
like image 111
Landei Avatar answered Oct 21 '22 04:10

Landei


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.

like image 25
Matthieu Saleta Avatar answered Oct 21 '22 03:10

Matthieu Saleta


Your code should look something like that:

persons.stream()
.map(person -> person.getName() + " " + person.getSurname)
.collect(Collectors.toList());
like image 31
matejetz Avatar answered Oct 21 '22 03:10

matejetz