要使用Lambda表达式使用现有列表中的值创建新列表,下面是一个示例。
在这里,我们显示员工的姓名。因此,我们也创建了一个Employee类-
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"));
使用Lambda通过Lambda Expressions从现有列表中创建新列表-
List<String>res = emp.stream().map(u ->u.displayEmpName()).collect(Collectors.toList());
让我们看完整的例子-
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; 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 = emp.stream().map(u ->u.displayEmpName()).collect(Collectors.toList()); System.out.println("Employee Names = "+res); } } 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; } }
输出结果
Employee Names = [Jack, Tom, Harry, Katie]