Sarah Szabo
Sarah Szabo

Reputation: 10815

Storing a New Instance In a Stream

If I have a stream of objects, can I turn it into a collection of another object? So if I have a collection of Strings can I turn it into a collection of Persons? Something like:

strings.stream().forEach((string) -> {new Person(string);}).collect(Collectors.toList());

public class Person{
private String name;

Person(String name){
this.name = name;
    }
}

Upvotes: 3

Views: 2737

Answers (2)

Eran
Eran

Reputation: 393781

That's what map is for :

List<Person> persons = strings.stream()
                      .map(s -> new Person(s))
                      .collect(Collectors.toList());

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533492

yes, I suggest you try it with map() instead of forEach

List<Person> people = strings.stream()
                             .map(Person::new)
                             .collect(Collectors.toList());

Note: while Person::new does the same thing as s -> new Person(s) it is not exactly the same. The Person::new doesn't create a lambda method but the latter does. In the byte code, you will see a synthetic method which contains the implementation.

Upvotes: 11

Related Questions