流是Java API的新成员,它允许以声明性方式处理数据集合(通过查询语句来表达,而不是临时编写一个实现)。
Java 7 从集合中选出低热量菜肴名称:
List<Dish> lowCaloricDishes = new ArrayList<>(); for (Dish d: menu) { if (d.getCalories() < 400) { lowCaloricDishes.add(d); } } Collections.sort(lowCaloricDishes, new Comparator<Dish>() { public int compare(Dish d1, Dish d2) { return Integer.compare(d1.getCalories(), d2.getCalories()); } }); List<String> lowCaloricDishesName = new ArrayList<>(); for(Dish d: lowCaloricDishes) { lowCaloricDishesName.add(d.getName()); }
Java 8 :
List<String> lowCaloricDishesName2 = menu.stream() .filter(d -> d.getCalories() < 400) .sorted(comparing(Dish::getCalories)) .map(Dish::getName) .collect(toList());
如果要多核架构并行执行这段代码,只需要把stream()换成parallelStream():
List<String> lowCaloricDishesName2 = menu.parallelStream() .filter(d -> d.getCalories() < 400) .sorted(comparing(Dish::getCalories)) .map(Dish::getName) .collect(toList());
时间: 2024-11-07 17:11:06