Java8新特性之streamAPI(四)

练习:

1.给定一个数字列表,如何返回一个由每个数的平方构成的列表?
  给定【1,2,3,4,5】,返回【1,4,9,16,25】
2.用map和reduce方法数一数流中一共用多少个Employee
package streamAPI;

import lambda.Employee;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;


public class TestStreamAPI {

    List<Employee> employees = Arrays.asList(
            new Employee("张三", 25, 9000, Employee.Status.FREE),
            new Employee("李四", 38, 10000, Employee.Status.BUSY),
            new Employee("王晓", 45, 12000, Employee.Status.FREE),
            new Employee("李华", 28, 9500, Employee.Status.FREE),
            new Employee("花花", 22, 8000, Employee.Status.VOCATION),
            new Employee("李华", 28, 9500, Employee.Status.VOCATION),
            new Employee("花花", 22, 8000, Employee.Status.BUSY),
            new Employee("花花", 22, 8000, Employee.Status.BUSY),
            new Employee("李华", 28, 9500, Employee.Status.BUSY),
            new Employee("花花", 22, 8000, Employee.Status.VOCATION)
    );

    /*
     *1.给定一个数字列表,如何返回一个由每个数的平方构成的列表?
     * 给定【1,2,3,4,5】,返回【1,4,9,16,25】
     */
    @Test
    public void test1() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        list.stream()
                .map((x) -> x * x)
                .forEach(System.out::println);
    }

    /*
     *2.用map和reduce方法数一数流中一共用多少个Employee
     */
    @Test
    public void test2() {
        Optional<Integer> count = employees.stream()
                .map((e) -> 1)
                .reduce(Integer::sum);
        System.out.println(count.get());
    }
}
相关函数声明详见: https://blog.csdn.net/qq_38358499/article/details/104636487
发布了111 篇原创文章 · 获赞 57 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_38358499/article/details/104642490

相关文章