Java8-Stream operation map,reduce

原创 2016年08月31日 11:36:46
package lambda;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class StreamOperationExam {
    /**
     *  A map operation applies a function to each element to produce another stream.
     *  The number of elements in the input and output streams is the same.
     *  The operation does not modify the elements of the input stream.
     *
     *  <R> Stream<R> map(Function<? super T,? extends R> mapper)
     *  DoubleStream  mapToDouble(ToDoubleFunction<? super T> mapper)
     *  IntStream     mapToInt(ToIntFunction<? super T> mapper)
     *  LongStream    mapToLong(ToLongFunction<? super T> mapper)
     *
     */
    public static void mapExam() {
        IntStream.rangeClosed(1, 5).map(n -> n * n).forEach(System.out::println);
    }

    /**
     *  Streams map() operation creates a one-to-one mapping.
     *  Streams flatMap() supports one-to-many mapping. 
     *  It maps each element to a stream and then flaten the stream of streams to a stream. 
     */
    public static void flatMapExam() {
        // result:1,2,2,3,3,4
        Stream.of(1, 2, 3).flatMap(n -> Stream.of(n, n + 1)).forEach(System.out::println);

        // convert a stream of strings to a stream of characters
        Stream.of("XML", "Java", "CSS").map(name -> name.chars())
                .flatMap(intStream -> intStream.mapToObj(n -> (char) n)).forEach(System.out::println);

        // flatMaps the stream of string values to a IntStreams, then maps IntStream to Stream of characters
        Stream.of("XML", "Java", "CSS").flatMap(name -> IntStream.range(0, name.length()).mapToObj(name::charAt))
                .forEach(System.out::println);
    }

    /**
     *  The reduce() operation combines all elements in a stream to produce a single value.
     *  The reduce operation takes two parameters called a seed (initial value) and an accumulator.
     *  The accumulator is a function. If the stream is empty, the seed is the result.
     *  The seed and an element are passed to the accumulator, which returns partial result.
     *  And then the partial result and the next element are passed to the accumulator function.
     *
     *  This repeats until all elements are passed to the accumulator.
     *  The last value returned from the accumulator is the result of the reduce operation.
     *
     *  The stream-related interfaces contain two methods called reduce()
     *  and collect() to perform generic reduce operations.
     *
     *  Methods such as sum(), max(), min(), count(), are defined in IntStream,
     *  LongStream, and DoubleStream interfaces.
     *
     *  count() method is available for all types of streams.
     *
     *  The Stream<T> interface contains a reduce() method to perform the reduce operation.
     *  The method has three overloaded versions:
     *
     *  T  reduce(T identity, BinaryOperator<T> accumulator)
     *  <U> U reduce(U identity, BiFunction<U,? super  T,U> accumulator, BinaryOperator<U> combiner)
     *  Optional<T> reduce(BinaryOperator<T> accumulator)
     */
    public static void reduceExam() {
        // takes an identity and an accumulator as arguments
        // and reduces the stream to a single value of the same type
        // T reduce(T identity, BinaryOperator<T> accumulator)
        // <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
        // Optional<T> reduce(BinaryOperator<T> accumulator)
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        int sum = numbers.stream().reduce(0, Integer::sum);
        System.out.println(sum);
    }

    /**
     * When using the following reduce method, each thread accumulates the partial results using the accumulator.
     * At the end, the combiner is used to combine the partial results from all threads to get the result.
     * <U> U reduce(U identity,
           BiFunction<U, ? super T, U> accumulator,
           BinaryOperator<U> combiner);
     */
    public static void reduceOp() {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        int id = 1;

        /**
         * print result:
         in peek,n=3
         in accumulator:a=1,b=3
         in peek,n=5
         in accumulator:a=1,b=5
         in peek,n=4
         in accumulator:a=1,b=4
         in combiner1:a=6,b=7
         in combiner1:a=5,b=13
         in peek,n=2
         in accumulator:a=1,b=2
         in peek,n=1
         in accumulator:a=1,b=1
         in combiner1:a=3,b=4
         in combiner1:a=7,b=18
         parallelStream,combiner1,result1=25
         */
        int result1 = numbers.parallelStream().peek(StreamOperationExam::peek).reduce(id,
                StreamOperationExam::accumulator, StreamOperationExam::combiner1);
        System.out.println("parallelStream,combiner1,result1=" + result1);
        System.out.println("-------------");

        /***
         * print result:
         in peek,n=3
         in accumulator:a=1,b=3
         in peek,n=5
         in accumulator:a=1,b=5
         in peek,n=4
         in accumulator:a=1,b=4
         in combiner2:a=6,b=7
         in combiner2:a=5,b=42
         in peek,n=2
         in accumulator:a=1,b=2
         in peek,n=1
         in accumulator:a=1,b=1
         in combiner2:a=3,b=4
         in combiner2:a=12,b=210
         parallelStream,combiner2,result2=2520
         */
        int result2 = numbers.parallelStream().peek(StreamOperationExam::peek).reduce(id,
                StreamOperationExam::accumulator, StreamOperationExam::combiner2);
        System.out.println("parallelStream,combiner2,result2=" + result2);
        System.out.println("-------------");

        /***
         * print result:
         in peek,n=1
         in accumulator:a=1,b=1
         in peek,n=2
         in accumulator:a=3,b=2
         in peek,n=3
         in accumulator:a=8,b=3
         in peek,n=4
         in accumulator:a=19,b=4
         in peek,n=5
         in accumulator:a=42,b=5
         stream,combiner1,result3=89
         */
        int result3 = numbers.stream().peek(StreamOperationExam::peek).reduce(id, StreamOperationExam::accumulator,
                StreamOperationExam::combiner1);
        System.out.println("stream,combiner1,result3=" + result3);
        System.out.println("-------------");

        /**
         * print result:
         in peek,n=1
         in accumulator:a=1,b=1
         in peek,n=2
         in accumulator:a=3,b=2
         in peek,n=3
         in accumulator:a=8,b=3
         in peek,n=4
         in accumulator:a=19,b=4
         in peek,n=5
         in accumulator:a=42,b=5
         stream,combiner2,result4=89
         */
        int result4 = numbers.stream().peek(StreamOperationExam::peek).reduce(id, StreamOperationExam::accumulator,
                StreamOperationExam::combiner2);
        System.out.println("stream,combiner2,result4=" + result4);
        System.out.println("-------------");
    }

    private static int combiner1(int a, int b) {
        System.out.println("in combiner1:a=" + a + ",b=" + b);
        return a + b;
    }

    private static int combiner2(int a, int b) {
        System.out.println("in combiner2:a=" + a + ",b=" + b);
        return a * b;
    }

    private static int accumulator(int a, int b) {
        System.out.println("in accumulator:a=" + a + ",b=" + b);
        return 2 * a + b;
    }

    private static void peek(int n) {
        System.out.println("in peek,n=" + n);
    }

    public static void main(String[] args) {
        reduceOp();
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Java 8 Stream API features --- map/reduce methods

在 jdk 1.8 里面新增加了 Stream API ,为了去更高效的处理 huge data。那么怎么使用这些 API 呢,一点一点了解,先走马观花看一遍: 要做的事情是先把每个 element...

Java 8 Stream API features --- filter/reduce & predicate Interface test method

现在要对下面一组 number ,过滤掉被5整除的,再*2 . jdk1.7 之前是这么做的: public static void main(String... args){ List value...

java8 Stream API之reduce

通过前面那篇文章,我们已经对Stream API有了初步的认识,并对它在集合处理中的增强作用表示了肯定。同时我们上篇中示例了forEach、fiter、sum这些常用的功能,本篇我们只讲reduce。...

[Java 8] (10) 使用Lambda完成函数组合,Map-Reduce以及并行化

Java 8中同时存在面向对象编程(OOP)和函数式编程(FP, Functional Programming)这两种编程范式。实际上,这两种范式并不矛盾,只是着重点不同。在OOP中,着重于通过丰富的...

java8新特性——函数式编程(stream/map)

今天看代码,发现部分字符串处理使用的是jdk8的新特性,非常简洁。从网上找了教程,方便以后编程使用。 package com.mavsplus.java8.turtorial.streams...

Java8之Stream/Map以及Lambda

引用自Java8之Stream/Map 本篇用代码示例结合JDk源码讲了Java8引入的工具接口Stream以及新Map接口提供的常用默认方法. 参考:http://winterbe.com...

Java 8系列之Stream中万能的reduce

reduce 操作可以实现从Stream中生成一个值,其生成的值不是随意的,而是根据指定的计算模型。比如,之前提到count、min和max方 法,因为常用而被纳入标准库中。事实上,这些方法都是re...

java实现map-reduce代码

本文记录用java实现map-reduce,并在服务器上运行的代码。 package com.demo.hadoop.test; import java.io.IOException; i...

Java 高阶函数的简单使用:map,reduce,filter,sorted

package cn.test;import java.util.ArrayList; import java.util.IntSummaryStatistics; import java.util....

java1.8一个不错的api调用栈(1)从Stream<?>创建一个Map

java8给集合排序
  • kkgbn
  • kkgbn
  • 2017-03-17 16:07
  • 462
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)