流操作之中间操作

package com.ant.jdk8.chap04;

import java.util.Arrays;
import java.util.List;

public class StreamDemo {
    public static void main(String[] args) {
        List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Type.MEAT),
                new Dish("beef", false, 700, Type.MEAT),
                new Dish("chicken", false, 400, Type.MEAT),
                new Dish("french fries", true, 530, Type.OTHER),
                new Dish("rice", true, 350, Type.OTHER),
                new Dish("season fruit", true, 120, Type.OTHER),
                new Dish("pizza", true, 550, Type.OTHER),
                new Dish("prawns", false, 300, Type.FISH),
                new Dish("salmon", false, 450, Type.FISH) );
        menu.stream()
                .filter(d->{
                    System.out.println("filtering "+d.getName());
                    return d.getCalories()>300;
                })
                .map(d->{
                    System.out.println("mapping "+d.getName());
                    return d.getName();
                })
                .limit(3);
    }
}

诸如filter或sorted等中间操作会返回另一个流。这让多个操作可以连接起来形成一个查询。重要的是,除非流水线上触发一个终端操作,否则中间操作不会执行任何处理。这是因为中间操作一般都可以合并起来,在终端操作时一次性全部处理。

package com.ant.jdk8.chap04;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamDemo {
    public static void main(String[] args) {
        List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Type.MEAT),
                new Dish("beef", false, 700, Type.MEAT),
                new Dish("chicken", false, 400, Type.MEAT),
                new Dish("french fries", true, 530, Type.OTHER),
                new Dish("rice", true, 350, Type.OTHER),
                new Dish("season fruit", true, 120, Type.OTHER),
                new Dish("pizza", true, 550, Type.OTHER),
                new Dish("prawns", false, 300, Type.FISH),
                new Dish("salmon", false, 450, Type.FISH) );
        menu.stream()
                .filter(d->{
                    System.out.println("filtering "+d.getName());
                    return d.getCalories()>300;
                })
                .map(d->{
                    System.out.println("mapping "+d.getName());
                    return d.getName();
                })
                .limit(3)
                .collect(Collectors.toList());
    }
}

你会发现,有好几种优化利用了流的延迟性质。

第一,尽管很多菜的热量都高于300卡路里,但只选出了前三个。这是因为limit操作和一种称为短路的技巧。

第二,尽管filter和map是两个独立的操作,但它们合并到同一次遍历中了(循环合并)。

猜你喜欢

转载自www.cnblogs.com/i-hard-working/p/9580284.html
今日推荐