一.流简介
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))