您当前的位置: 首页 > 

梁云亮

暂无认证

  • 3浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Stream API ---- 规约Reduce

梁云亮 发布时间:2019-10-22 17:00:39 ,浏览量:3

Stream 规约

规约操作(reduction operation)又被称作折叠操作(fold),是通过某个连接动作将所有元素汇总成一个汇总结果的过程。元素求和、求最大值或最小值、求出元素总个数、将所有元素转换成一个列表或集合,都属于规约操作。Stream类库有两个通用的规约操作reduce()和collect(),也有一些为简化书写而设计的专用规约操作,比如sum()、max()、min()、count()等。 reduce()擅长的是生成一个值,collect()擅长从Stream中生成一个集合或者Map等复杂的对象!

reduce()函数的功能是从一组元素中生成一个值。sum()、max()、min()、count()等都是reduce操作,将他们单独设为函数只是因为常用。reduce()的方法定义有三种重写形式:

  • Optional reduce(BinaryOperator accumulator)
  • T reduce(T identity, BinaryOperator accumulator)
  • U reduce(U identity, BiFunction accumulator, BinaryOperator combiner) 参数说明:
    • identity:指明初始值
    • accumulator:
    • combiner:指定并行执行时多个部分结果的合并方式
示例1:
  public static void main(String[] args) {
        //求和
        Arrays.stream(new Integer[]{2, 4, 6, 8})
                .reduce((i, j) -> i + j)
                .ifPresent(System.out::println); //20
        Integer res1 = Arrays.stream(new Integer[]{2, 4, 6, 8})
                .reduce(0, Integer::sum);
        System.out.println(res1);  //20

        //求最大值
        Arrays.stream(new Integer[]{2, 4, 6, 8})
                .reduce(Integer::max)
                .ifPresent(System.out::println); //8

        //求最小值
        Arrays.stream(new Integer[]{2, 4, 6, 8})
                .reduce(Integer::min)
                .ifPresent(System.out::println); //2

        //做逻辑
        Arrays.stream(new Integer[]{2, 4, 6, 8})
                .reduce((item1, item2) -> item1 > item2 ? item2 : item1)
                .ifPresent(System.out::println); //2

        //求乘
        int result2 = Arrays.stream(new Integer[]{2, 4, 6, 8})
                .filter(i -> i % 2 == 0)
                .reduce(1, (i, j) -> i * j);
        Optional.of(result2).ifPresent(System.out::println);//384
    }
示例2:从一组单词中找出最长的单词
public static void main(String[] args) {
    Optional res = Stream.of("zhangsan", "lisi", "wanger", "mazi")
            .reduce((s1, s2) -> s1.length() >= s2.length() ? s1 : s2);
    System.out.println(res.get());  //zhangsan

    Optional res2 = Stream.of("zhangsan", "lisi", "wanger", "mazi")
            .max((s1, s2) -> s1.length() - s2.length());
    System.out.println(res2.get()); //zhangsan
}
示例3:求出一组单词的长度之和
 public static void main(String[] args) {
    int res = Stream.of("zhangsan", "lisi", "wanger", "mazi")
            .reduce(0, //初始值
                    (sum, str) -> sum + str.length(),   //累加器 // -------①
                    (a, b) -> a + b //部分拼接器,并行执行时才会用到
            );
    System.out.println(res); //22
    int sum = Stream.of("zhangsan", "lisi", "wanger", "mazi")
            .mapToInt(item -> item.length())
            .sum();
    System.out.println(sum); //22
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0475s