map()
接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
eg
:将employees中Employee的名字汇总成一个String集合
List<Employee> employees = new ArrayList<>();
{
employees.add(new Employee(1,"张三",20,8895.31));
employees.add(new Employee(2,"张四",28,7894.34));
employees.add(new Employee(3,"张柳",46,6895.37));
employees.add(new Employee(66,"王一",54,5895.5));
employees.add(new Employee(56,"李四",55,4895.8));
employees.add(new Employee(89,"李十一",32,9895.354));
employees.add(new Employee(546,"张十五",20,18895.37));
employees.add(new Employee(43,"刘十六",43,28895.35));
employees.add(new Employee(43,"刘十六",43,28895.35));
}
/**
* 测试map方法
* 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
*/
@Test
public void testStreamMap() {
List<String> employeeName = new ArrayList<>();
List<Employee> collect = employees.stream().map(employee -> {
//可以对元素进行操作
employeeName.add(employee.getName());
return employee;
}).collect(Collectors.toList());
collect.forEach(System.out::println);
employeeName.forEach(System.out::println);
}
/**
* 测试mapToDouble方法
* 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
*/
@Test
public void testStreamMapToDouble() {
DoubleStream doubleStream = employees.stream().mapToDouble(Employee::getSalary);
doubleStream.forEach(System.out::println);
}
/**
* 测试mapToInt方法
* 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
*/
@Test
public void testStreamMapToInt() {
IntStream intStream = employees.stream().mapToInt(Employee::getIndex);
intStream.forEach(System.out::println);
}
没学会