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

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

具体用法

public class Collectors_example {

    public static void main(String[] args) {
List<Apple> appleList = new ArrayList<>();
appleList.add(new Apple("red", 170));
appleList.add(new Apple("green", 150));
appleList.add(null);
appleList.add(new Apple("yellow", 170));
appleList.add(new Apple("green", 100));
appleList.add(new Apple("red", 170)); //joining: 拼接
String join = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining());
String join1 = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining("-"));
String join2 = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining("-", "前缀", "后缀"));
System.out.println(join2); //toCollection、toList与toSet
ArrayList<Integer> arrayList = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toCollection(ArrayList::new));
List<Integer> arrayList1 = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toList());
Set<Integer> hashSet = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toSet()); System.out.println("----------------------------------");
//toMap与toConcurrentMap: 键不能重复!!! toConcurrentMap同toMap
Map<String, Integer> map4 = appleList.stream().collect(Collectors.toMap(Apple::getColor, Apple::getWeight));
Map<Integer, Integer> map5 = appleList.stream().collect(Collectors.toMap(Apple::getWeight, x -> 1, Integer::sum));
Hashtable<Integer, Integer> hashtable = appleList.stream().collect(Collectors.toMap(Apple::getWeight, x -> 1, Integer::sum, Hashtable::new));
System.out.println(map5);
System.out.println(hashtable); //reducing: 对输入元素执行汇聚操作
Apple apple = appleList.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparingInt(Apple::getWeight)))).orElse(null);
Integer inte = appleList.stream().map(x -> x.getWeight()).collect(Collectors.reducing(10000, Integer::sum));
Integer inte1 = appleList.stream().collect(Collectors.reducing(0, Apple::getWeight, Integer::sum));
System.out.println(inte1); /******************求值: list中如果存在空元素会抛空指针异常!!******************/
//averaging: 平均值
//averagingInt/averagingLong/averagingDouble
Double collect = appleList.stream().collect(Collectors.averagingDouble(Apple::getWeight));
System.out.println(collect); //counting: 统计个数
Long count = appleList.stream().collect(Collectors.counting());
Long emptyCount = Stream.empty().collect(Collectors.counting());
//Stream.count()方法的返回值是long型,counting()方法返回值是Collector类型
long streamCount = appleList.stream().count();
System.out.println(count);
System.out.println(emptyCount); //maxBy、minBy: 最大最小值
appleList.stream().collect(Collectors.maxBy(Comparator.comparingInt(Apple::getWeight))).ifPresent(System.out::println);
appleList.stream().collect(Collectors.minBy(Comparator.comparingInt(Apple::getWeight))).ifPresent(System.out::println); //summing、summarizing: 求和
Integer sum1 = appleList.stream().collect(Collectors.summingInt(Apple::getWeight));
IntSummaryStatistics iss = appleList.stream().collect(Collectors.summarizingInt(Apple::getWeight));
System.out.println(iss.getMax());
System.out.println(iss.getMin());
System.out.println(iss.getCount());
System.out.println(iss.getSum());
System.out.println(iss.getAverage()); /******************分组******************/
//groupingBy: 分组
Map<String, List<Apple>> map = appleList.stream().collect(Collectors.groupingBy(Apple::getColor));
Map<String, Long> longMap = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.counting()));
TreeMap<String, Long> treeMap = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, TreeMap::new, Collectors.counting()));
longMap.forEach((k, v) -> {
System.out.println(k + ":" + v);
}); //groupingByConcurrent: 操作同groupingBy; 元素整理成ConcurrentMap(线程安全)
ConcurrentMap<String, List<Apple>> map1 = appleList.stream().collect(Collectors.groupingByConcurrent(Apple::getColor)); //partitioningBy: 分区;例:大于150的一个组,小于150的一个组
Map<Boolean, List<Apple>> map2 = appleList.stream().collect(Collectors.partitioningBy(x -> x.getWeight() > 150));
Map<Boolean, Long> map3 = appleList.stream().collect(Collectors.partitioningBy(x -> x.getWeight() > 150, Collectors.counting()));
map3.forEach((k, v) -> {
System.out.println(k + ":" + v);
}); //collectingAndThen: 收集后操作
String avg = appleList.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Apple::getWeight), item -> "average weight is " + item));
System.out.println(avg); //mapping: 在调用mapper之后,将调用结果的返回值作为downstream的输入元素,再调用downstream
String collect1 = appleList.stream().collect(Collectors.mapping(Apple::getColor, Collectors.joining("-")));
System.out.println(collect1); } /******************自定义******************/
public static <T> Collector<T, Set<T>, Set<T>> toImmutableSet() {
return Collector.of(HashSet::new, Set::add, (left, right) -> {
left.addAll(right);
return left;
}, t -> t, Collector.Characteristics.IDENTITY_FINISH);
} public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
return Collector.of(
supplier,
Set::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableSet);
} }

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. centos 安装docker方法2

    1 更新yum yum -y update 2 执行命令 linux 安装dockersudo wget -qO- https://get.docker.com | sh解释如下sudo 使用root ...

  2. linux磁盘空间满的处理

    Java中运行SQL插入数据时报错: linux磁盘空间满处理: 1.df -h  查看磁盘空间占用,实际上是查看磁盘块占用的文件(block) 2.分别查看输入以下命令 (面对磁盘满了,通过下列命令 ...

  3. 第十二章 LNMP架构之分离数据库

    一.课程回顾 1.搭建LNMP环境 1.配置官方源2.yum安装依赖3.yum安装nginx4.配置nginx5.创建用户6.启动并加入开机自启​7.上传安装包8.解压安装包9.卸载旧版本PHP10. ...

  4. 微信小程序项目wx-store代码详解

    这篇文章会很长,非常长,特别长,无敌长. 真的是挤牙膏般的项目进度,差不多是8月底有开始这个项目的想法,时至今日都1个多月了,抛去频繁的加班时间,王者时间,羽毛球时间...见缝插针的写这个项目,我竟然 ...

  5. vue-awesome-swiper ---移动端h5 swiper 和 tab 栏选项联动效果实现

    很久之前做小程序时有个类似每日优鲜里储值卡充值界面里的 卡轮播和价格tab栏联动效果,当时觉得新鲜做出来之后也没当回事.直到今天又遇到了一个类似的功能,所以想着总结经验. 实现效果如下图: 图解:点击 ...

  6. 关于 Deployer 部署结构

    Deployer 部署完成后,在服务器上的结构会是这样子: drwxr-sr-x 5 deployer www-data 4096 Jun 14 09:53 ./ drwxr-sr-x 6 deplo ...

  7. 【原创】linux实时操作系统xenomai x86平台基准测试(benchmark)

    一.前言 benchmark 即基准测试.通常操作系统主要服务于应用程序,其运行也是需要一定cpu资源的,一般来说操作系统提供服务一定要快,否则会影响应用程序的运行效率,尤其是实时操作系统.所以本文针 ...

  8. Layui treeSelect 回写与对应选中

    今天遇到个问题就是Layui treeSelect 的回写与特定选中,网络上居然没啥资料,有的也是不全的,于是花了点时间处理好了,这里写一下,方便以后有遇到的朋友借鉴. 一.父页面 二.Form编辑框 ...

  9. SpringBoot第一集:入门(2020最新最易懂)

    2020最新SpringBoot第一集:入门(2020最新最易懂) 学习思路: 是什么?为什么要学,有什么用?有什么特点?简单明了的总结一句话! SpringBoot推荐开发工具: Spring To ...

  10. spring3.X版本知识点

    一.SpringMVC重点注解 @Controller 1.@Controller 与 @Component 实际应用中作用等价.     2.和Struct一样,也是单例,意味着被多个请求线程共享, ...