Java 8系列之Stream的基本语法详解02


Stream流是java8中很重要的一项技能:

之前操作java代码, 执行过滤操作:

public class SimpleStream {

    public static void main(String[] args) {

        List 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 names = getDishNamesByCollections(menu);
        System.out.println(names);
    }

    private static List getDishNamesByCollections(List menu){
        List lowCal = new ArrayList<>();
//遍历 for (Dish dish : menu) { if (dish.getCalories() < 400){ lowCal.add(dish); } } //排序 Collections.sort(lowCal, (d1, d2) -> Integer.compare(d1.getCalories(), d2.getCalories())); List dishNameList = new ArrayList<>();
     //遍历 for (Dish d : lowCal) { dishNameList.add(d.getName()); } return dishNameList; } }

  可以把上面的代码以Stream的形式来做:

//stream方法来做
private static List getDishNamesByStream(List menu){
    //先过滤,然后排序,最后以map的key,返回集合
    List collect = menu.stream().filter(dish -> dish.getCalories() < 400)
                .sorted(Comparator.comparing(Dish::getCalories)).map(Dish::getName).collect(Collectors.toList());

    return collect;
}