在Java 8中,我们可以使用带有lambda表达式的Stream对象的map()方法将对象转换为另一种类型。 map()方法是流对象中的中间操作,因此我们需要一种终端方法来完成流。
<R>Stream <R> map(Function<? super T,? extends R> mapper)
import java.util.*; import java.util.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表达式 .collect(Collectors.toList()); System.out.println(names); } } //Employee类 class Employee { private String empName; private String empDesignation; public Employee(String empName) { this.empName = empName; } public String getEmployeeName() { return empName; } public void setEmployeeName(String empName) { this.empName = empName; } public String getEmployeeDesignation() { return empDesignation; } public void setEmployeeDesignation(String empDesignation) { this.empDesignation = empDesignation; } }
输出结果
[Jai, Adithya, Raja]