Collector是专门用来作为Stream的collect方法的参数的;而Collectors是作为生产具体Collector的工具类。

Collectors是一个工具类,是JDK预实现Collector的工具类,它内部提供了多种Collector,我们可以直接拿来使用,非常方便。

具体用法

  1. public class Collectors_example {
  2.  
  3. public static void main(String[] args) {
  4. List<Apple> appleList = new ArrayList<>();
  5. appleList.add(new Apple("red", 170));
  6. appleList.add(new Apple("green", 150));
  7. appleList.add(null);
  8. appleList.add(new Apple("yellow", 170));
  9. appleList.add(new Apple("green", 100));
  10. appleList.add(new Apple("red", 170));
  11.  
  12. //joining: 拼接
  13. String join = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining());
  14. String join1 = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining("-"));
  15. String join2 = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining("-", "前缀", "后缀"));
  16. System.out.println(join2);
  17.  
  18. //toCollection、toList与toSet
  19. ArrayList<Integer> arrayList = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toCollection(ArrayList::new));
  20. List<Integer> arrayList1 = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toList());
  21. Set<Integer> hashSet = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toSet());
  22.  
  23. System.out.println("----------------------------------");
  24. //toMap与toConcurrentMap: 键不能重复!!! toConcurrentMap同toMap
  25. Map<String, Integer> map4 = appleList.stream().collect(Collectors.toMap(Apple::getColor, Apple::getWeight));
  26. Map<Integer, Integer> map5 = appleList.stream().collect(Collectors.toMap(Apple::getWeight, x -> 1, Integer::sum));
  27. Hashtable<Integer, Integer> hashtable = appleList.stream().collect(Collectors.toMap(Apple::getWeight, x -> 1, Integer::sum, Hashtable::new));
  28. System.out.println(map5);
  29. System.out.println(hashtable);
  30.  
  31. //reducing: 对输入元素执行汇聚操作
  32. Apple apple = appleList.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparingInt(Apple::getWeight)))).orElse(null);
  33. Integer inte = appleList.stream().map(x -> x.getWeight()).collect(Collectors.reducing(10000, Integer::sum));
  34. Integer inte1 = appleList.stream().collect(Collectors.reducing(0, Apple::getWeight, Integer::sum));
  35. System.out.println(inte1);
  36.  
  37. /******************求值: list中如果存在空元素会抛空指针异常!!******************/
  38. //averaging: 平均值
  39. //averagingInt/averagingLong/averagingDouble
  40. Double collect = appleList.stream().collect(Collectors.averagingDouble(Apple::getWeight));
  41. System.out.println(collect);
  42.  
  43. //counting: 统计个数
  44. Long count = appleList.stream().collect(Collectors.counting());
  45. Long emptyCount = Stream.empty().collect(Collectors.counting());
  46. //Stream.count()方法的返回值是long型,counting()方法返回值是Collector类型
  47. long streamCount = appleList.stream().count();
  48. System.out.println(count);
  49. System.out.println(emptyCount);
  50.  
  51. //maxBy、minBy: 最大最小值
  52. appleList.stream().collect(Collectors.maxBy(Comparator.comparingInt(Apple::getWeight))).ifPresent(System.out::println);
  53. appleList.stream().collect(Collectors.minBy(Comparator.comparingInt(Apple::getWeight))).ifPresent(System.out::println);
  54.  
  55. //summing、summarizing: 求和
  56. Integer sum1 = appleList.stream().collect(Collectors.summingInt(Apple::getWeight));
  57. IntSummaryStatistics iss = appleList.stream().collect(Collectors.summarizingInt(Apple::getWeight));
  58. System.out.println(iss.getMax());
  59. System.out.println(iss.getMin());
  60. System.out.println(iss.getCount());
  61. System.out.println(iss.getSum());
  62. System.out.println(iss.getAverage());
  63.  
  64. /******************分组******************/
  65. //groupingBy: 分组
  66. Map<String, List<Apple>> map = appleList.stream().collect(Collectors.groupingBy(Apple::getColor));
  67. Map<String, Long> longMap = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.counting()));
  68. TreeMap<String, Long> treeMap = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, TreeMap::new, Collectors.counting()));
  69. longMap.forEach((k, v) -> {
  70. System.out.println(k + ":" + v);
  71. });
  72.  
  73. //groupingByConcurrent: 操作同groupingBy; 元素整理成ConcurrentMap(线程安全)
  74. ConcurrentMap<String, List<Apple>> map1 = appleList.stream().collect(Collectors.groupingByConcurrent(Apple::getColor));
  75.  
  76. //partitioningBy: 分区;例:大于150的一个组,小于150的一个组
  77. Map<Boolean, List<Apple>> map2 = appleList.stream().collect(Collectors.partitioningBy(x -> x.getWeight() > 150));
  78. Map<Boolean, Long> map3 = appleList.stream().collect(Collectors.partitioningBy(x -> x.getWeight() > 150, Collectors.counting()));
  79. map3.forEach((k, v) -> {
  80. System.out.println(k + ":" + v);
  81. });
  82.  
  83. //collectingAndThen: 收集后操作
  84. String avg = appleList.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Apple::getWeight), item -> "average weight is " + item));
  85. System.out.println(avg);
  86.  
  87. //mapping: 在调用mapper之后,将调用结果的返回值作为downstream的输入元素,再调用downstream
  88. String collect1 = appleList.stream().collect(Collectors.mapping(Apple::getColor, Collectors.joining("-")));
  89. System.out.println(collect1);
  90.  
  91. }
  92.  
  93. /******************自定义******************/
  94. public static <T> Collector<T, Set<T>, Set<T>> toImmutableSet() {
  95. return Collector.of(HashSet::new, Set::add, (left, right) -> {
  96. left.addAll(right);
  97. return left;
  98. }, t -> t, Collector.Characteristics.IDENTITY_FINISH);
  99. }
  100.  
  101. public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
  102. return Collector.of(
  103. supplier,
  104. Set::add, (left, right) -> {
  105. left.addAll(right);
  106. return left;
  107. }, Collections::unmodifiableSet);
  108. }
  109.  
  110. }

Collectors工具类的更多相关文章

  1. JDK1.8新特性——Collector接口和Collectors工具类

    JDK1.8新特性——Collector接口和Collectors工具类 摘要:本文主要学习了在Java1.8中新增的Collector接口和Collectors工具类,以及使用它们在处理集合时的改进 ...

  2. JDK在线API及常用工具类

    API http://tool.oschina.net/apidocs/apidoc?api=jdk-zh Java SE常用工具类 java.util.Arrays java.util.Collec ...

  3. redistemplate优雅地操作redis redis 工具类

    参考:https://www.cnblogs.com/superfj/p/9232482.html redis 工具类 package com.service; import org.springfr ...

  4. java高并发系列 - 第16天:JUC中等待多线程完成的工具类CountDownLatch,必备技能

    这是java高并发系列第16篇文章. 本篇内容 介绍CountDownLatch及使用场景 提供几个示例介绍CountDownLatch的使用 手写一个并行处理任务的工具类 假如有这样一个需求,当我们 ...

  5. java树形结构工具类

    一.树形结构数据一般都是以子父id的形式存在数据库中,查询的时候只是带有子id和parent_id的List集合 并不是树形结构,所以我们现在要将普通的List集合转换为树结构数据(本工具类扩展操作树 ...

  6. 带有连接池的Http客户端工具类HttpClientUtil

    一.背景 业务开发中,经常会遇到通过http/https向下游服务发送请求.每次都要重复造轮子写HttpClient的逻辑,而且性能.功能参差不齐.这里分享一个高性能的.带连接池的通用Http客户端工 ...

  7. java.util.concurrent中的几种同步工具类

    java.util.concurrent并发包中提供了一系列的的同步工具类,这些基础类不管是否能在项目中使用到,了解一下使用方法和原理对java程序员来说都是有必要的.博主在看<java并发编程 ...

  8. java代码(12) ---CollectionUtils工具类

    CollectionUtils工具类 CollectionUtils工具类是在apache下的,而不是springframework下的CollectionUtils 个人觉得在真实项目中Collec ...

  9. 【工具类】Stream流构建指定长度的时间集合

    package com.gabriel.stage.utils; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.Dat ...

随机推荐

  1. linux(centos8):安装java jdk 15 (java 15)

    一,下载jdk15 官方网站: https://www.oracle.com/java/ 下载页面: https://www.oracle.com/cn/java/technologies/javas ...

  2. nginx 快速安装

    必要条件 1能访问外网 2防火墙放开80 3有软件安装权限 依次执行以下命令 一.设置CentOS7的yum源及EPEL yum源 wget -O /etc/yum.repos.d/epel.repo ...

  3. Spring官方都推荐使用的@Transactional事务,为啥我不建议使用!

    GitHub 17k Star 的Java工程师成神之路,不来了解一下吗! GitHub 17k Star 的Java工程师成神之路,真的不来了解一下吗! GitHub 17k Star 的Java工 ...

  4. win8怎样才能启用administrator登录 别的用户也是如此

    但是你可以用命令调出administrator账户打开C盘,打开windows文件夹,再打开system32文件夹,找到cmd.exe右键点击选择以管理员身份运行 在里面输入net user admi ...

  5. Redis 入门与 ASP.NET Core 缓存

    目录 基础 Redis 库 连接 Redis 能用 redis 干啥 Redis 数据库存储 字符串 订阅发布 RedisValue ASP.NET Core 缓存与分布式缓存 内存中的缓存 ASP. ...

  6. 腾讯云大学 x CODING | 知识分享月直播预告

    经历十年的发展,DevOps 已经变成被广泛认知的研发效能方法论.DevOps 工具链作为 DevOps 落地的核心技术实践之一,在自动化和质量方面使得开发团队可以更快更好地交付产品,提高其竞争力. ...

  7. Zotero导入Markdown here插件

    1. 下载Markdown Here源码包 网址:https://github.com/adam-p/markdown-here 2. 创建.xpi后缀文件 将文件夹 中的这几个文件放入同一个文件夹中 ...

  8. layui 的基本使用介绍

    全局配置 layui.config({ dir: '/res/layui/' //layui.js 所在路径(注意,如果是script单独引入layui.js,无需设定该参数.),一般情况下可以无视 ...

  9. 一篇理解什么是CanSet, CanAddr?

    什么是可设置( CanSet ) 首先需要先明确下,可设置是针对 reflect.Value 的.普通的变量要转变成为 reflect.Value 需要先使用 reflect.ValueOf() 来进 ...

  10. ORA-01078: failure in processing system parameters 问题的解决方法(oracle 11g)

    https://blog.csdn.net/lzwgood/article/details/26358725