Partha Partha - 3 months ago 9
Java Question

Converting a List of Strings to a List of custom made objects in Java using Lambda Expression

So I have something like this :

List<String> persons = Arrays.asList("Tom","Harry", "Steve");


I want to convert it to a
List<Person>
using Lambda Expressions.

Assume Person is the following class :

class Person {
private String name;
public void setName(String name) {
this.name = name;
}

public String getName() {
return this.name;
}
}


I have been trying various things with forEach, map, etc, but not able to get the code to work.

Thanks.

Answer

If you add a constructor to your Person class that takes a string, you can just use:

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

If you don't have a constructor, then you will need a lambda:

List<Person> people = persons.stream()
    .map(s -> { Person p = new Person(); p.setName(s); return p; })
    .collect(Collectors.toList());