JAVA 8 Stream使用(一)

一.流简介

1.定义:从支持数据处理操作的源生成的元素序列。

1)元素序列----和集合一样,提供一个接口,可以访问特定一组有序值。

2)源---流使用的数据源

3)数据处理操作--类似于数据库的处理操作,流操作可以顺序执行,也可并行执行

4)流水线---很多流操作本身会返回一个流,这样可以链接起来,形成大的流水线。流操作可以看做对数据源进行数据库式查询。

5)内部迭代---和显式迭代器不一样,是背后执行的,

  List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chicken", false, 400, Dish.Type.MEAT),
                new Dish("french fries", true, 530, Dish.Type.OTHER),
                new Dish("rice", true, 350, Dish.Type.OTHER),
                new Dish("season fruit", true, 120, Dish.Type.OTHER),
                new Dish("pizza", true, 500, Dish.Type.OTHER),
                new Dish("prawns", true, 550, Dish.Type.FISH),
                new Dish("salmon", false, 300, Dish.Type.FISH)
                );
        List<String> threeHighCaloriesDishNames=
                menu.stream()  //从menu获取菜单流
                .filter(d->d.getCalories()>300)  //建立操作流水线;首先选出高热量的菜肴
                .map(Dish::getName)//获取菜名
                .limit(3)  //只选择头3个
                .collect(toList()); //将结果保存在另一个List中
        System.out.println(threeHighCaloriesDishNames); //输出结果[pork, beef, chicken]

    }

注意:流只能消费一次

List<String> title = Arrays.asList("JAVA","IN","ACTION");
        Stream<String> s = title.stream();
        s.forEach(System.out::println);
        s.forEach(System.out::println);---会报错(Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
	at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
	at com.fjs.myblog.stream.DishTest.main(DishTest.java:35))

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值