Java8之Stream API

1、Stream关注的是对数据的运算,与CPU打交道;集合关注的是数据的存储,与内存打交道。
2、
(1)Stream不会存储元素;
(2)Stream不会改变源对象,相反,会返回一个持有结果的新Stream;
(3)Stream操作是延迟执行的,意味着会等到需要结果的时候才执行。
3、Stream API执行流程:
(1)Stream的实例化;

	//创建Stream的方法1:通过集合
    @Test
    public void test1() {
        List<Employee> employees = EmployeeData.getEmployees();
        // 串行流
        Stream<Employee> stream = employees.stream();
        // 并行流
        Stream<Employee> parallelStream = employees.parallelStream();
    }

    // 创建Stream的方式2:通过数组
    @Test
    public void test2() {
        int[] arr = new int[]{1,2,3,4,5,6};
        // 调用Arrays类的static<T> Stream<T> stream(T[] array)返回一个流
        IntStream stream = Arrays.stream(arr);

        Employee e1 = new Employee(1001,"Tom");
        Employee e2 = new Employee(1001,"Jerry");
        Employee[] arr1 = new Employee[]{e1,e2};
        Stream<Employee> stream1 = Arrays.stream(arr1);
    }

    //创建Stream的方式3:通过Stream的of()
    @Test
    public void test3() {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
    }

    //创建Stream的方式4:创建无限流(了解)
    @Test
    public void test4() {
        // 迭代:
        // public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
        // 遍历前10个偶数
        Stream.iterate(0,t -> t + 2).limit(10).forEach(System.out::println);

        // 生成
        // public static<T> Stream<T> generate(Supplier<T> s)
        Stream.generate(Math::random).limit(10).forEach(System.out::println);
    }

(2)一系列的中间操作

	//筛选
    @Test
    public void test1() {
        List<Employee> employees = EmployeeData.getEmployees();
        // filter(Predict p):接收Lambda,从流中排出某些元素
        // 查询员工表中薪资大于9000的员工信息
        employees.stream().filter(e -> e.getSalary() > 9000).forEach(System.out::println);
        System.out.println();

        // limit(n):截断流,使其元素不超过给定数量
        employees.stream().limit(3).forEach(System.out::println);
        System.out.println();

        // skip(n):跳过元素,返回一个扔掉了前n个元素的流;若流中元素不足n个,则返回一个空流。limit(n)互补
        employees.stream().skip(2).forEach(System.out::println);
        System.out.println();

        // distinct():筛选,通过流所生成元素的hashCode()和equals()去除重复元素
        employees.add(new Employee(1010,"tom",40,10000.00));
        employees.add(new Employee(1010,"tom",40,10000.00));
        employees.add(new Employee(1010,"tom",40,10000.00));
        employees.stream().distinct().forEach(System.out::println);
    }

(3)终止操作
4、说明:
(1)一个中间操作链,对数据源的数据进行处理。
(2)一旦执行终止操作,就执行中间操作链,并产生结果,之后,不会再被使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值