Java8: Stream

写在前面: Java8的Stream用起来真的不是通常的爽。当你看到Stream的操做后,相信你不再会去写各类for循环、嵌套for循环,特别是作报表,体会更深.java

What is Stream?

流(Stream)是Java API的新成员,它容许以声明性的方式处理数据集合(相似于数据库查询语句).暂且理解为遍历数据集的高级迭代器.git

先举个例子尝尝鲜:github

/*
需求: 获取菜单中热量小于400卡路里的菜肴名称,并按照卡路里排序.
*/
@Data
@Accessor(chain = true)
public class Dish {
    // 该类将会在本文中屡次用到
    // omit getter,setter and constructor
    private String name;
    private boolean vegetarian;
    private int calories;
    private Type type;

    public enum Type {MEAT, FISH, OTHER}
}

// 普通写法
public static List<String> getLowCaloricDishesNamesInJava7(List<Dish> dishes){
    List<Dish> lowCaloricDishes = new ArrayList<>();
    for(Dish d: dishes){
        if(d.getCalories() < 400){
            lowCaloricDishes.add(d);
        }
    }
    List<String> lowCaloricDishesName = new ArrayList<>();
    Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
        public int compare(Dish d1, Dish d2){
            return Integer.compare(d1.getCalories(), d2.getCalories());
        }
    });
    for(Dish d: lowCaloricDishes){
        lowCaloricDishesName.add(d.getName());
    }
    return lowCaloricDishesName;
}
// Stream 写法
public static List<String> getLowCaloricDishesNamesInJava8(List<Dish> dishes){
    return dishes.stream()
        .filter(d -> d.getCalories() < 400)
        .sorted(comparing(Dish::getCalories))
        .map(Dish::getName)
        .collect(toList());
}

从上面的代码能够明显看出区别,Stream写法更加简短、优美,而且可读性很强,我看到这段代码我就知道是干什么的.这就引伸出Stream的优势:数据库

  • 声明性 -- 更简洁,更易读(表达能力很强)
  • 可复合 -- 更灵活(可过滤,可映射,可排序...)
  • 可并行 -- 性能更好(使用parallelStream)

Introduce of Stream

流就是从支持数据处理操做的源生成的元素序列数组

  • 元素序列: 我理解的存储流数据的数据结构(?)
  • 源: 提供数据的源,如集合,数组,输入/输出资源等.从有序集合生成流时会保留原有的顺序.
  • 数据处理操做: filter,sort,map,find...流操做能够顺序执行,也能够并行执行.

Stream and Collection

集合是数据结构,因此它的主要目的是存储和访问集合元素,但流的目的是在于计算.数据结构

集合讲的是数据,集合能够遍历无数次,而流只能遍历一次,遍历完以后咱们就说这个流被消费掉了.准确的说,流只能被消费一次,那些终端操做都是消费流.app

Stream<Integer> s = Arrays.asList(1,2,3,4).stream();
s.forEach(System.out.print);  // 打印:1 2 3 4
s.forEach(System.out.print);  // 无打印

Inner Iteration and Outer Iteration

使用集合须要咱们本身去作迭代(好比for-each),这就叫外部迭代.相反,Stream库使用内部迭代,也就是不须要咱们去作迭代.好比:ide

// 仍是上面那个Dish类,假设有个对象List<Dish> menu, 要打印menu中全部菜肴的名称
// 外部迭代
for(Dish d : menu) {
    System.out.println(d.getName());
}
// 内部迭代
menu.stream().map(Dish::getName).forEach(System.out::println);

Operations of Stream

先看一个例子:函数

menu.stream().filter(d -> d.getCalories() > 300).map(Dish::getName).forEach(System.out::println);
  • 生成流: menu.steam(),生成流的方式有好多,如Arrays.stream(),可本身去查看Java API
  • 中间操做(流的延迟性质): 处理流并返回流,好比filter,map,distinct等,相似fluent API.
  • 终端操做: 消费流数据,好比forEach,collect等.

流的延迟性质

若是流水线上没有触发一个终端操做,那么中间操做是不会对流数据进行处理的.这是由于中间操做通常能够合并起来,在终端操做时一次性处理.好比:性能

List<String> names = menu.stream().filter(d -> {
        System.out.println("filtering");
        return d.getCalories() > 300;
    }).map(d -> {
        System.out.println("mapping");
        return d.getName();
    }).limit(3).collect(toList());
/*
上述的代码输出:
    filtering
    mapping
    filtering
    mapping
    filtering
    mapping
*/

从上述的打印结果明显能够看出来,流会对中间操做进行合并,尽管filter和map是两个独立的操做,但它们合并到同一次遍历中了(循环合并).

Common Operations

不少流操做的方法参数类型都是函数式接口,这些函数式接口都是JDK自带的,本文将不会解释这些函数式接口,能够本身看接口的定义.

操做 类型 参数类型 函数描述符 描述
filter 中间 Predicate<T> T -> Boolean 过滤
distinct 中间 去重
skip 中间 long 跳过前几项
limit 中间 long 只取前几项
map 中间 Function<T,R> T -> R 映射
flatMap 中间 Function<T,Stream<R>> T -> Stream<R> 扁平化流
sorted 中间 Comparator<T> (T,T) -> int 排序
anyMatch 终端 Predicate<T> T -> Boolean 任意项匹配
noneMatch 终端 Predicate<T> T -> Boolean 无匹配
allMatch 终端 Predicate<T> T -> Boolean 全部匹配
findAny 终端 返回任意项
findFirst 终端 返回第一项
forEach 终端 Consumer<T> T -> void 遍历流
collect 终端 Collector<T,A,R> 收集流数据
reduce 终端 BinaryOperator<T> (T,T) -> T 归约
count 终端 long 数量

上面这些都是经常使用的流操做,顺便提一下,使用skip和limit还能够作分页操做.下面讲解一下map,flatMap,reduce

映射: map

映射,也就是我从一个数据通过某些操做变成了另外一个数据,也就是x --> y

x --f(x)--> y

举个栗子:

// 获取List<Dish> menu中全部菜肴的名称
Stream<Dish> ds = menu.stream();  //菜单流
Stream<String> ns = menu.stream().map(e -> e.getName());  //菜肴名称流

扁平化: flatMap

扁平化流,这是<<Java8实战>>中这么翻译的,按我我的理解的话,我以为flatMap就是合并流:

Stream<T> + Stream<T> + Stream<T> ==> Stream<R>

举个栗子:

// 有一个String集合,须要将每一个String切分红字符,并去重
List<String> ss = Arrays.asList("Hello", "World")
                        .stream()                   // Stream<String>
                        .map(e -> e.split(""))      // Stream<String[]>
                        .flatMap(Arrays::stream)    // Stream<String>
                        .distinct()
                        .collect(toList());
ss.forEach(System.out::print);
/*
输出:
Helowrd
*/

对于上面这个栗子,执行map操做后返回Stream<String[]>(String[]指的是流元素的类型),接下来执行flatMap,将String[] -> Stream<String>, 而后将多个Stream<String>合并成一个Stream<String>.
下面这张图能够很形象地解释flatMap.
stream-flatMap

归约: reduce

归约这个说法不太好理解,查看词典reduce还有个解释是"概括为".wiki上对于归约的解释:

所谓的归约是将某个计算问题转换为另外一个问题的过程。

也就是说reduce是描述如何从一个计算问题转换为另外一个问题.大概是这么理解的吧.嗯,应该就是这样理解的(有木有大佬帮忙解释一下...〒︿〒).仍是举几个栗子吧.

/*
计算一个数值集合的总和
*/
Integer sum = Arrays.asList(4, 5, 3, 9).stream().reduce(0, (a, b) -> a + b);
// 计算问题: 计算List<Integer>的总和
// 过程: reduce, 转换为另外一个问题"能够设置一个初值为0, 而后每次累加, 也就是(a, b) -> a + b"
// (可能理解有误)

/*
求一个数值集合的最大值
*/
Integer max = Arrays.asList(1, 2, 3, 4, 5).stream().reduce(Integer::max).orElse(0);

至于reduce方法具体是如何实现的,一步一步累加的过程,能够看下图:stream-reduce.png

reduce有三个重载方法,可根据须要使用对应的方法.

T reduce(T identity, BinaryOperator<T> accumulator);
    Optional<T> reduce(BinaryOperator<T> accumulator);
    <U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> cobiner);

使用上面三个方法的时候要注意函数式接口的类型,以及泛型,下面我举个例子,计算菜单中全部的菜肴的热量总和,声明一点,下面的写法是很是很差的写法(shit code),只是单纯用来比较reduce三个重载方法的用法,以及写的时候要注意函数式接口的类型

Dish sum1 = dishes.stream().reduce(new Dish(), (a, b) -> new Dish().setCalories(a.getCalories() + b.getCalories()));
System.out.println(sum1.getCalories());

Dish sum2 = dishes.stream().reduce((a, b) -> new Dish().setCalories(a.getCalories() + b.getCalories())).get();
System.out.println(sum2.getCalories());

// 第三个参数暂时还不知道什么用处
Integer sum3 = dishes.stream().reduce(0, (c, d) -> c + d.getCalories(), (a, b) -> a - b);
System.out.println(sum3);

固然上面那个求和也能够这么写: Arrays.asList(4, 5, 3, 9).stream().mapToInt(e -> e).sum(),其实sum的实现也是调的reduce方法.这里的mapToInt是转化成一个IntStream(数值流).

Numerical Stream

举个例子:

int calories = menu.stream().map(Dish::getCalories).reduce(0, Integer::sum);

这段代码的的问题是,它有一个暗含装箱的成本(为何是装箱,而不是拆箱的成本?).

Java8引入了三个原始类型特化流接口来解决这个问题: IntStream,LongStream,DoubleStream,分别将流中的元素特化为int,long,double,从而避免了暗含的装箱成本.映射到数值流,可使用mapToInt,mapToLong,mapToDouble,而转换为对象流直接调用boxed()方法便可.

Java8为数值流提供了不少的方法,好比sum,min,max,count,average等等.如今我们就可使用数值流来计算菜单中全部菜肴的热量总和:

int calories = menu.stream().mapToInt(Dish::getCalories).sum();

Summary

  • 在Stream中使用了大量的函数式接口,结合上一篇博客来讲的话,流是函数式接口的最佳实践,那么使用流是Lambda表达式的最佳实践
  • Stream的专一点是处理数据,只能被消费一次(终端操做),而集合的重点是在于存取
  • Stream的写法简短易读,一目了然
  • Stream的经常使用操做,除了flatMap和reduce不太好理解,其余的都是顾名思义
  • 数值流,减小了装箱的成本
相关文章
相关标签/搜索