Java Collection How to - Create a new list with values from fields from existing list with Lambda








Question

We would like to know how to create a new list with values from fields from existing list with Lambda.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/*from  w ww  .  j  a  v  a 2s . co m*/
public class Main {
  public static void main(String args[]) {
    List<Person> people = Arrays.asList(new Person("B", 25, "Main Street"),
        new Person("A", 27, "Off Street"));
    List<String> listNames = people.stream().map(u -> u.getName())
        .collect(Collectors.toList());
    System.out.println(listNames);
  }
}

class Person {
  private String name;
  private int age;
  private String location;

  public Person(String name, int age, String location) {
    this.name = name;
    this.age = age;
    this.location = location;
  }

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

Output :