Java Program to create a new list with values from existing list with Function Mapper


To create a new list with values from fields from existing list with Function Mapper, the following is an example. Here, we have a class Employee −

class Employee {
   private String emp_name;
   private int emp_age;
   private String emp_zone;
}

The following is an example that creates a new list from existing with Function Mapper −

Example

 Live Demo

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class Demo {
   public static void main(String args[]) {
      List < Employee > emp = Arrays.asList(new Employee("Jack", 29, "South"), new Employee("Tom", 24, "North"),
         new Employee("Harry", 35, "West"), new Employee("Katie", 32, "East"));
      List < String > res = processElements(emp, p -> p.displayEmpName());
      System.out.println("Employee Names + " + res);
   }
   public static < X, Y > List < Y > processElements(Iterable < X > src,
   Function < X, Y > mapper) {
      List < Y > list = new ArrayList <> ();
      for (X p: src)
         list.add(mapper.apply(p));
      return list;
   }
}
class Employee {
   private String emp_name;
   private int emp_age;
   private String emp_zone;
   public Employee(String emp_name, int emp_age, String emp_zone) {
      this.emp_name = emp_name;
      this.emp_age = emp_age;
      this.emp_zone = emp_zone;
   }
   public String displayEmpName() {
      return this.emp_name;
   }
}

Output

Employee Names + [Jack, Tom, Harry, Katie]

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements