流是什么,以及流的操作(Java 8 的新特性)

1.流是什么?

属于一个 Java API

1. 可以以声明性的方式来处理数据集合,就像 SQL 语句似的,加一个 where 过滤条件

2. 还可以进行并行处理

 

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

List<String> lowCaloricDishesName = menu.stream()
                                      .filter(d->d.getCalories()<400)   // 筛选卡路里小于400
                                      .sorted(comparing(Dish::getCalories)) //按卡路里排序
                                      .map(Dish::getName)     // 取出菜名
                                      .collect(toList());      //放到集合中

 

如果想使用 多核处理,可以将 stream 方法替换为 parallelStream 的方法。

 

参看 https://gitee.com/coder_xiaozhao/java8-demo  中的Application.java 中的一个简单演示

		// 菜单集合
		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,550,Dish.Type.OTHER),
				new Dish("prawns",false,300,Dish.Type.FISH),
				new Dish("salmon",false,450,Dish.Type.FISH)
				);
		List<String> threeHighCaloricDishNames = 
				menu.stream()    // 从 menu 获得流(菜肴列表)
				.filter(d->d.getCalories()>300)  //建立操作流水xian
				.map(Dish::getName)
				.limit(3)
				.collect(toList());   //将结果保存在另一个List 中
		System.out.println(threeHighCaloricDishNames);

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值