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








Question

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

Answer

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
//from  w w  w .j  a va  2  s.  c  o 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> lNames = processElements(people, p -> p.getName()); // for the
                                                                     // names

    System.out.println(lNames);
  }

  public static <X, Y> List<Y> processElements(Iterable<X> source,
      Function<X, Y> mapper) {
    List<Y> l = new ArrayList<>();
    for (X p : source)
      l.add(mapper.apply(p));
    return l;
  }

}

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;
  }
}

The code above generates the following result.