sparsh610
sparsh610

Reputation: 1601

Java stream : convert list of one object to other

I am trying to learn map function in Stream

public class EmployeeInformationTest {
   public static void main(String args[]) {
      List<Employee> employees = Arrays.asList(
         new Employee("Jai"),
         new Employee("Adithya"),
         new Employee("Raja"));
      List<String> names = employees.stream()
         .map(s -> s.getEmployeeName())              // Lambda Expression
         .collect(Collectors.toList());
      System.out.println(names);
   }
}

we have above code and somehow it is giving us List of String from List of Employee. Say, we have other class Person in which we have field as name

public class Person {
    private String name;
}

so is it feasible via map or some other function in stream so that I can get the List of Person rather than List of String in above code

Upvotes: 0

Views: 1227

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

sure thing, just change the map function to:

.map(s -> new Person(s.getEmployeeName()))   

or if there is no such constructor:

.map(s -> { 
    Person p = new Person();
    p.setName(s.getEmployeeName());
    return p;
}) 

Upvotes: 1

Related Questions