Java8 Stream Collectors收集器使用方法解析

所属分类: 软件编程 / java 阅读数: 60
收藏 0 赞 0 分享

Collectors.toMap:

Student studentA = new Student("20190001","小明");
    Student studentB = new Student("20190002","小红");
    Student studentC = new Student("20190003","小丁");


    //Function.identity() 获取这个对象本身,那么结果就是Map<String,Student> 即 id->student
    //串行收集
   Stream.of(studentA,studentB,studentC)
        .collect(Collectors.toMap(Student::getId,Function.identity()));

    //并发收集
    Stream.of(studentA,studentB,studentC)
        .parallel()
        .collect(Collectors.toConcurrentMap(Student::getId,Function.identity()));

    //================================================================================

    //Map<String,String> 即 id->name
    //串行收集
    Stream.of(studentA,studentB,studentC)
        .collect(Collectors.toMap(Student::getId,Student::getName));

    //并发收集
    Stream.of(studentA,studentB,studentC)
        .parallel()
        .collect(Collectors.toConcurrentMap(Student::getId,Student::getName));

那么如果key重复的该怎么处理?这里我们假设有两个id相同Student,如果他们id相同,在转成Map的时候,取name大一个,小的将会被丢弃。

//Map<String,Student>  //maxby ==sordBy  倒序 minBy or .maxBy(Comparator.comparing(User::getName).reversed())));
    Stream.of(studentA, studentB, studentC)
        .collect(Collectors
            .toMap(Student::getId,
                Function.identity(),
                BinaryOperator
                    .maxBy(Comparator.comparing(Student::getName))));

    
    //可能上面比较复杂,这编写一个命令式
    //Map<String,Student>
    Stream.of(studentA, studentB, studentC)
        .collect(Collectors
            .toMap(Student::getId,
                Function.identity(),
                (s1, s2) -> {
              
                  //这里使用compareTo 方法 s1>s2 会返回1,s1==s2 返回0 ,否则返回-1
                  if (((Student) s1).name.compareTo(((Student) s2).name) < -1) {
                    return s2;
                  } else {
                    return s1;
                  }
                }));

如果不想使用默认的HashMap 或者 ConcurrentHashMap , 第三个重载方法还可以使用自定义的Map对象(Map工厂)。

//自定义LinkedHashMap
    //Map<String,Student>
    Stream.of(studentA, studentB, studentC)
        .collect(Collectors
            .toMap(Student::getId,
                Function.identity(),
                BinaryOperator
                    .maxBy(Comparator.comparing(Student::getName)),
                LinkedHashMap::new));

Collectors.groupingBy()和Collectors.groupingByConcurrent(),这两者区别也仅是单线程和多线程的使用场景。为什么要groupingBy归类为前后处理呢?groupingBy 是在数据收集前分组的,再将分好组的数据传递给下游的收集器。

这是 groupingBy最长的参数的函数classifier 是分类器,mapFactory map的工厂,downstream下游的收集器,正是downstream 的存在,可以在数据传递个下游之前做很多的骚操作。

public static <T, K, D, A, M extends Map<K, D>>
  Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier,
                 Supplier<M> mapFactory,
                 Collector<? super T, A, D> downstream) 

示例:这里将一组数整型数分为正数、负数、零,groupingByConcurrent()的参数也是跟它一样的就不举例了。

//Map<String,List<Integer>>
    Stream.of(-6, -7, -8, -9, 1, 2, 3, 4, 5, 6)
        .collect(Collectors.groupingBy(integer -> {
          if (integer < 0) {
            return "小于";
          } else if (integer == 0) {
            return "等于";
          } else {
            return "大于";
          }
        }));

    //Map<String,Set<Integer>>
    //自定义下游收集器
    Stream.of(-6, -7, -8, -9, 1, 2, 3, 4, 5, 6)
        .collect(Collectors.groupingBy(integer -> {
          if (integer < 0) {
            return "小于";
          } else if (integer == 0) {
            return "等于";
          } else {
            return "大于";
          }
        },Collectors.toSet()));

    //Map<String,Set<Integer>>
    //自定义map容器 和 下游收集器
    Stream.of(-6, -7, -8, -9, 1, 2, 3, 4, 5, 6)
        .collect(Collectors.groupingBy(integer -> {
          if (integer < 0) {
            return "小于";
          } else if (integer == 0) {
            return "等于";
          } else {
            return "大于";
          }
        },LinkedHashMap::new,Collectors.toSet()));

Collectors.partitioningBy()

字面意思话就叫分区好了,但是partitioningBy最多只能将数据分为两部分,因为partitioningBy分区的依据Predicate,而Predicate只会有true 和false 两种结果,所有partitioningBy最多只能将数据分为两组。partitioningBy除了分类器与groupingBy 不一样外,其他的参数都相同。

示例:

//Map<Boolean,List<Integer>>
    Stream.of(0,1,0,1)
        .collect(Collectors.partitioningBy(integer -> integer==0));

    //Map<Boolean,Set<Integer>>
    //自定义下游收集器
    Stream.of(0,1,0,1)
        .collect(Collectors.partitioningBy(integer -> integer==0,Collectors.toSet()));

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

SpringBoot中使用Ehcache的详细教程

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认的 CacheProvider。这篇文章主要介绍了SpringBoot中使用Ehcache的相关知识,需要的朋友可以参考下
收藏 0 赞 0 分享

在idea 中添加和删除模块Module操作

这篇文章主要介绍了在idea 中添加和删除模块Module操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java spring整合junit操作(有详细的分析过程)

这篇文章主要介绍了java spring整合junit操作(有详细的分析过程),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解JAVA 弱引用

这篇文章主要介绍了 JAVA 弱引用的相关资料,帮助大家更好的理解和学习java引用对象,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

深入了解JAVA 虚引用

这篇文章主要介绍了JAVA 虚引用的相关资料,帮助大家更好的理解和学习JAVA,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

详解JAVA 强引用

这篇文章主要介绍了JAVA 强引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

java中的按位与(&)用法说明

这篇文章主要介绍了java中的按位与(&)用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

深入了解JAVA 软引用

这篇文章主要介绍了JAVA 软引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

利用MyBatis实现条件查询的方法汇总

这篇文章主要给大家介绍了关于利用MyBatis实现条件查询的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用MyBatis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
收藏 0 赞 0 分享

Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.PathTranslator was bound

这篇文章主要介绍了Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.Pa
收藏 0 赞 0 分享
查看更多