java stream

http://www.jianshu.com/p/c53eb31752c4

 

一. 四种最基本的函数式接口


使用Stream类进行流操作之前,先了解一下四种最基本的函数式接口(根据英文单词意思就可以理解其作用):

  1. Predicate<T> 接口:一个T类型参数,返回boolean类型值。
    boolean test(T t);
    Lambda表达式基本写法:
    Predicate<Integer> predicate = x -> x > 5;
  2. Function<T, R> 功能接口:一个T类型参数,返回R类型值。
    R apply(T t);
    Lambda表达式基本写法:
    Function<Integer, Integer> function = x -> x + 1;
  3. Supplier<T> 接口:无参数,返回一个T类型值。
    T get();
    Lambda表达式基本写法:
    Supplier<Integer> supplier = () -> 1;
  4. Consumer<T> 接口:一个T类型参数,无返回值。
    void accept(T t);
    Lambda表达式基本写法:
    Consumer<Integer> consumer = x -> System.out.println(x);
    Consumer<Integer> consumer = System.out::println;//方法引用的写法

“->”符号的左侧对应的是方法参数,无参数就空括号,一个参数可以省略括号,多参数不能省略,比如(x,y);
“->”符号的右侧对应的是方法返回值,整体是一个代码块{...},最终返回值对应方法即可。比如Function<Integer, Integer> function = x -> {return x + 1};当只有一个表达式时,{}、return均可省略。
以上函数式接口的抽象方法都是单个参数,多个参数有BiPredicate、BiFunction、BiConsumer等接口,用法类似。

Optional 不是函数是类,这是个用来防止NullPointerException的辅助类型。T get()

二. 使用Stream类进行流操作


下面开始使用Stream类进行流操作,除了Stream类,还有IntStream、DoubleStream、LongStream,很显然这三种都是有针对性的流操作,分别针对int、double、long类型的数据,它们都继承BaseStream类,如下图所示:


继承关系图.png
继承关系图.png
一. 怎么创建Stream类?

四种方式:

1. Stream<T> stream = Stream.of(T... values);
2. Stream<Object> build = Stream.builder().add(1).add(2).build();
3. Stream<Integer> iterate= Stream.iterate(0, x -> x + 1).limit(3);
4. Stream<String> generate = Stream.generate(() -> "hello world").limit(3);

3和4两种方式一定要加limit()限制数量,不然就突破天际了~
常用的数组、集合数据操作都可以转换成流操作。** 数组可以通过Arrays类中的stream(...)方法转换成Stream,集合可以通过Collection接口中的stream()方法转换成Stream。**

IntStream stream = Arrays.stream(new int[]{1, 3, 4});
Stream<Integer> stream = new ArrayList<Integer>().stream();
二. 使用Stream类进行数据操作
  1. allMatch(Predicate<? super T> predicate) :全部匹配
    System.out.println(Stream.of("peter", "anna", "mike").allMatch(s -> s.startsWith("a")));
    打印结果:false
    anyMatch:有一个匹配就返回true
    noneMatch:全部都不匹配才返回true

  2. filter(Predicate<? super T> predicate);:过滤操作,返回Stream,可以进行链式调用
    Stream.of("peter", "anna", "mike").filter(value -> value.startsWith("a")).collect(Collectors.toList()).forEach(System.out::println);
    打印结果:anna

  3. map:映射操作,返回Stream
    Stream.of("peter", "anna", "mike").map(String::toUpperCase).collect(Collectors.toList()).forEach(System.out::println);
    打印结果:PETER ANNA MIKE

  4. flatMap:将最底层元素抽出来放到一起
    Stream.of(Arrays.asList(1, 2, 3), Arrays.asList(2, 3, 6)).flatMap(lists -> lists.stream()).collect(Collectors.toList()).forEach(System.out::print);
    打印结果:123236
    Stream<List<Integer>> listStream = Stream.of(Arrays.asList(1, 2, 3), Arrays.asList(2, 3, 6));
    listStream.flatMap(lists -> lists.stream()).collect(Collectors.toList()).forEach(System.out::print);
    listStream经过flatMap操作,变成了Stream<Integer>类型。

  5. concat:流连接操作
    Stream.concat(Stream.of(1, 2), Stream.of(3)).forEach(System.out::print);
    打印结果:123

  6. peek:生成一个包含原Stream的所有元素的新Stream,新Stream每个元素被消费之前都会执行peek给定的消费函数
    Stream.of(2, 4).peek(x -> System.out.print(x - 1)).forEach(System.out::print);
    打印结果:1234

  7. skip:跳过前N个元素后,剩下的元素重新组成一个Stream
    Stream.of(1, 2, 3, 4).skip(2).forEach(System.out::print);
    打印结果:34

  8. max:最大值,存在求最大值,肯定就有求最小值。min
    System.out.println(Stream.of(1, 2, 3, 4).max(Integer::compareTo).get());
    打印结果:4

  9. reduce:网上翻译为规约,用途比较广,可以作为累加器,累乘器,也可以用来实现map、filter操作。
    Java8提供了三个方法:
    1. Optional<T> reduce(BinaryOperator<T> accumulator);
    2. T reduce(T identity, BinaryOperator<T> accumulator);
    3. <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
    第2个相对于第1个来说,除了返回值不同,就只是多了一个初始值。
    System.out.println(Arrays.asList(1, 2, 3).stream().reduce((a, b) -> a + b).get());
    System.out.println(Arrays.asList(1, 2, 3).stream().reduce(0, (a, b) -> a + b));
    打印结果都是6。
    第3个方法第3个参数是在使用并行流操作的时候,最后进行汇集操作,所以串行流使用前面两种方法即可。
    Stream有串行和并行两种,调用stream()或sequential()就成为了串行流,调用parallelStream()或parallel()就成为了并行流,两者同时调用,只需看最后一次调用的方法即可。并行流在某些条件下可以提高性能,但这里只介绍一些API,性能问题暂时不讨论。

  10. 其他还有distinct、count、sorted等方法,作用跟SQL语句一样。

上篇Java8之Stream类限于篇幅,所以把Stream的collect方法单独拿出来写一篇文章。
Stream API中有两种collect方法:

1. <R, A> R collect(Collector<? super T, A, R> collector);
2. <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);

一般第一种方法用的比较多,第二种方法看起来跟reduce的第三种方法有点类似,也可以用来实现filter、map等操作,但是两者实现方式有区别。我们以实现filter为例:

  • reduce实现filter功能方式:
public static <T> List<T> filter(Stream<T> stream, Predicate<T> predicate) {
    return stream.reduce(new ArrayList<T>(), (acc, t) -> {
        if (predicate.test(t)) {
            List<T> lists = new ArrayList<T>(acc);
            lists.add(t);
            return lists;
        }
        return acc;
    }, (List<T> left, List<T> right) -> {
        List<T> lists = new ArrayList<T>(left);
        lists.addAll(right);
        return lists;
    });
}
  • collect实现filter功能方式:
public static <T> List<T> filter(Stream<T> stream, Predicate<T> predicate) {
    return stream.collect(ArrayList::new, (acc, t) -> {
        if (predicate.test(t))
            acc.add(t);
    }, ArrayList::addAll);
}

很明显collect实现方式更简洁,效率更高。reduce为什么每次都new一次ArrayList,直接acc.add(t)再返回acc呢呢?因为reduce规定第二个参数BiFunction<U, ? super T, U> accumulator表达式不能改变其自身参数acc原有值,所以每次都要new ArrayList<T>(acc),再返回新的list。

下面来看看第一种collect方法,它离不开Collectors工具类。其实上篇的代码已经涉及到了该方法,比如collect(Collectors.toList())转换成list集合。其他API如下:

  1. Collectors.toSet():转换成set集合。
  2. Collectors.toCollection(TreeSet::new):转换成特定的set集合。
     TreeSet<Integer> collect2 = Stream.of(1, 3, 4).collect(Collectors.toCollection(TreeSet::new));
  3. Collectors.toMap(x -> x, x -> x + 1):转换成map。
     Map<Integer, Integer> collect1 = Stream.of(1, 3, 4).collect(Collectors.toMap(x -> x, x -> x + 1));
  4. Collectors.minBy(Integer::compare):求最小值,相对应的当然也有maxBy方法。
  5. Collectors.averagingInt(x->x):求平均值,同时也有averagingDouble、averagingLong方法。
      System.out.println(Stream.of(1, 2, 3).collect(Collectors.averagingInt(x->x)));
  6. Collectors.summingInt(x -> x)):求和。
  7. Collectors.summarizingDouble(x -> x):可以获取最大值、最小值、平均值、总和值、总数。
     DoubleSummaryStatistics summaryStatistics = Stream.of(1, 3, 4).collect(Collectors.summarizingDouble(x -> x));
     summaryStatistics.getAverage();//平均值
  8. Collectors.groupingBy(x -> x)有三种方法,查看源码可以知道前两个方法最终调用第三个方法,第二个参数默认HashMap::new 第三个参数默认Collectors.toList(),参考SQL的groupBy。
     Map<Integer, List<Integer>> map = Stream.of(1, 3, 3, 4).collect(Collectors.groupingBy(x -> x));
     Map<Integer, Long> map = Stream.of(1, 3, 3, 4).collect(Collectors.groupingBy(x -> x, Collectors.counting()));
     HashMap<Integer, Long> hashMap = Stream.of(1, 3, 3, 4).collect(Collectors.groupingBy(x -> x, HashMap::new, Collectors.counting()));
  9. Collectors.partitioningBy(x -> x > 2),把数据分成两部分,key为ture/false。第一个方法也是调用第二个方法,第二个参数默认为Collectors.toList()。
     Map<Boolean, List<Integer>> collect5 = Stream.of(1, 3, 4).collect(Collectors.partitioningBy(x -> x > 2));
     Map<Boolean, Long> collect4 = Stream.of(1, 3, 4).collect(Collectors.partitioningBy(x -> x > 2, Collectors.counting()));
  10. Collectors.joining(","):拼接字符串。
    System.out.println(Stream.of("a", "b", "c").collect(Collectors.joining(",")));
  11. Collectors.reducing(0, x -> x + 1, (x, y) -> x + y)):在求累计值的时候,还可以对参数值进行改变,这里是都+1后再求和。跟reduce方法有点类似,但reduce方法没有第二个参数。
    System.out.println(Stream.of(1, 3, 4).collect(Collectors.reducing(0, x -> x + 1, (x, y) -> x + y)));
  12. Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d"):先执行collect操作后再执行第二个参数的表达式。这里是先拼接字符串,再在最后+ "d"。
    String str= Stream.of("a", "b", "c").collect(Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d"));
  13. Collectors.mapping(...):跟map操作类似,只是参数有点区别。
    System.out.println(Stream.of("a", "b", "c").collect(Collectors.mapping(x -> x.toUpperCase(), Collectors.joining(","))));

下篇Lambda表达式的真实面目



posted @ 2017-11-01 18:04  Bigben  阅读(218)  评论(0编辑  收藏  举报