lambda表达式Stream流学习十—Stream操作练习题,map、sorted、collect、filter、forEach、max、min
一,map 与 reduce 复习
/*
1) 给定一个数字列表, 如何返回一个由每个数平方构成的列表呢, 给定[1, 2, 3, 4, 5], 应该返回[1, 4, 5, 16, 25]
map—接收 Lambda,将元素转换为其他形式或提取信息,接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
*/
@Test
public void test1(){
Integer[] arr = new Integer[]{
1, 2, 3, 4, 5};
System.out.println(Arrays.stream(arr).map((e) -> e*e).collect(Collectors.toList()));
}
/*
怎么用 map 和 reduce 方法数一数流中有多少个 Employee
归约 : reduce(T identity, BinaryOperator) / reduce(BinaryOperator)——可以将流中的元素反复结合起来,做指定的操作,得到一个值
*/
@Test
public void test2(){
List<Employee> list = Arrays.asList(
new Employee("张三", 18, 9999.99),
new Employee("李四", 20, 7777.77),
new Employee("王五", 36, 5555.55),
new Employee("赵六", 50, 3333.33),
new Employee("田七", 10, 2222.22)
);
System.out.println(list.stream().map