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);