• One bite of Stream(7)


    流的收集器

    我们前面看到过这样的收集器:

    List transactions = transactionStream.collect(Collectors.toList());

    会把流中的数据依次填充到List中并返回。

    1. 统计数量counting()

    long howManyDishes = menu.stream().collect(Collectors.counting());

    counting算收集器的一种,就是对流中元素的个数进行计数,也可以使用count简化

    long howManyDishes = menu.stream().count();

    2. 最大值、最小值maxBy() minBy()

    1. Optional mostCalorieDish = menu.stream()
    2. .collect(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories)));

    通过Comparator.comparingInt()可以生成一个比较器

    Collectors.maxBy用于获取最大值

    同理,最小值使用minBy()

    3. 求和汇总summingInt()、summingLong()、summingDouble()

    int total = menu.stream().collect(Collectors.summingInt(Dish::getCalories));

    summingInt()用于求和,内部支持方法引用进行映射。

     同样的,summingLong() summingDouble()也是类似的使用方法。

    4. 求均值汇总averagingInt()、averagingLong()、averagingDouble()

    double avg = menu.stream().collect(averagingInt(Dish::getCalories));

    averagingInt对元素进行均值运算,接收方法引用进行映射

    同样的,也支持averagingLong() averagingDouble()

    5. 汇总summarizingInt()、summarizingLong()、summarizingDouble()

    前面我们用到了counting()、maxBy()、minBy()、summingInt()、averagingInt(),现在使用summarizingInt()可以包含前面所有。

    1. IntSummaryStatistics menuStatistics = menu.stream()
    2. .collect(summarizingInt(Dish::getCalories));

    IntSummaryStatistics就是统计数据的结果集:

    IntSummaryStatistics{count=9, sum=4300, min=120, average=477.777778, max=800}

    包含计数、求和、最小值、最大值、均值。

    同样的,summarizingLong()、summarizingDouble()也可以使用,对应的结果集为LongSummaryStatistics、DoubleSummaryStatistics

    6. 字符串拼接joining()

    String shortMenu = menu.stream().collect(joining());

    joining()默认调用toString()方法,使用StringBuilder进行拼接,也支持使用分隔符进行拼接。

    String shortMenu = menu.stream().map(Dish::getName).collect(joining(", "));
  • 相关阅读:
    【SA8295P 源码分析 (三)】132 - GMSL2 协议分析 之 GPIO/SPI/I2C/UART 等通迅控制协议带宽消耗计算
    如下面第一个图的九宫格中,放着 1~8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。
    echarts 学习网址
    set和multiset容器
    15. 机器学习——聚类
    Oralce ORA-00018超出最大会话数处理记录
    Linux学习之HIS部署(4)
    MySQL高阶语句
    使用watch和tail命令监控文件内容的变化
    如何使用 JMeter 进行 HTTPS 请求测试?
  • 原文地址:https://blog.csdn.net/Day_and_Night_2017/article/details/125884546