• 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(", "));
  • 相关阅读:
    社区买菜系统 毕业设计 JAVA+Vue+SpringBoot+MySQL
    百数水印体系更新-让数据操作更安全
    远程访问及控制
    零数科技创新金融案例入选《2022全球区块链创新应用示范案例集》
    centos7离线安装neo4j
    2024年度“阳江市惠民保”正式发布!阳江市专属补充医疗保险全新升级
    boot引导升级,成功引导运行loader
    [车联网安全自学篇] 五十四. Android安全之剪贴板+键盘缓存+UI界面+自动截屏敏感信息挖掘
    JKTD-1000型铁电材料测试仪
    Java面向对象——多态
  • 原文地址:https://blog.csdn.net/Day_and_Night_2017/article/details/125884546