JDK1.8新特性(五): Collectors

JDK1.8新特性(五): Collectors一 简介 JDK1 8 中 Map 新增了一些方法 其中一部分方法是为了简化代码的 如 forEach 另外一些方法是为了防止 null 使操作代码更加严谨 二 Mappublicint amp amp amp lt K V amp amp amp gt 如果 key 存在 则忽略 put 操作 defaultVputI Kkey Vvalue V

大家都在看的人 工 智 能,通俗易懂,简单易解,风趣幽默

一:简介

Stream中有两个个方法collect和collectingAndThen用于对流中的数据进行处理,可以对流中的数据进行聚合操作,如:

  • 将流中的数据转成集合类型: toList、toSet、toMap、toCollection
  • 将流中的数据(字符串)使用分隔符拼接在一起:joining
  • 对流中的数据求最大值maxBy、最小值minBy、求和summingInt、求平均值averagingDouble
  • 对流中的数据进行映射处理 mapping
  • 对流中的数据分组:groupingBy、partitioningBy
  • 对流中的数据累计计算:reducing
 
  
    R collect(Collector 
    collector); // collectingAndThen : 将流中的数据通过Collector计算,最终的结果在通过Function再最终处理一下 public static 
   
     Collector 
    
      collectingAndThen(Collector 
     
       downstream, Function 
      
        finisher); 
       
      
     
    
  

Collectors

public final class Collectors { // 转换成集合 public static 
  
    Collector 
   
     > toList(); public static 
    
      Collector 
     
       > toSet(); public static 
      
        Collector 
       
         > toMap(Function 
         keyMapper, Function 
         valueMapper); public static 
        
          > Collector 
         
           toCollection(Supplier 
          
            collectionFactory); // 拼接字符串,有多个重载方法 public static Collector 
           
             joining(CharSequence delimiter); public static Collector 
            
              joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix); // 最大值、最小值、求和、平均值 public static 
             
               Collector 
              
                > maxBy(Comparator 
                comparator); public static 
               
                 Collector 
                
                  > minBy(Comparator 
                  comparator); public static 
                 
                   Collector 
                  
                    summingInt(ToIntFunction 
                    mapper); public static 
                   
                     Collector 
                    
                      averagingDouble(ToDoubleFunction 
                      mapper); // 分组:可以分成true和false两组,也可以根据字段分成多组 public static 
                     
                       Collector 
                      
                        >> groupingBy(Function 
                        classifier); // 只能分成true和false两组 public static 
                       
                         Collector 
                        
                          >> partitioningBy(Predicate 
                          predicate); // 映射 public static 
                         
                           Collector 
                          
                            mapping(Function 
                            mapper, Collector 
                            downstream); public static 
                           
                             Collector 
                            
                              reducing(U identity, Function 
                              mapper, BinaryOperator 
                              op); }  
                             
                            
                           
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
  

二:示例

流转换成集合
@Test public void testToCollection(){ List 
   
     list = Arrays.asList(1, 2, 3); // [10, 20, 30] List 
    
      collect = list.stream().map(i -> i * 10).collect(Collectors.toList()); // [20, 10, 30] Set 
     
       collect1 = list.stream().map(i -> i * 10).collect(Collectors.toSet()); // {key1=value:10, key2=value:20, key3=value:30} Map 
      
        collect2 = list.stream().map(i -> i * 10).collect(Collectors.toMap(key -> "key" + key/10, value -> "value:" + value)); // [1, 3, 4] TreeSet 
       
         collect3= Stream.of(1, 3, 4).collect(Collectors.toCollection(TreeSet::new)); } 
        
       
      
     
   
@Data @ToString @AllArgsConstructor @RequiredArgsConstructor public class User { private Long id; private String username; } @Test public void testToMap() { List 
   
     userList = Arrays.asList( new User(1L, "mengday"), new User(2L, "mengdee"), new User(3L, "mengdy") ); // toMap 可用于将List转为Map,便于通过key快速查找到某个value Map 
    
      userIdAndModelMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity())); User user = userIdAndModelMap.get(1L); // User(id=1, username=mengday) System.out.println(user); Map 
     
       userIdAndUsernameMap = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername)); String username = userIdAndUsernameMap.get(1L); // mengday System.out.println(username); } 
      
     
   
集合元素拼接
@Test public void testJoining(){ // a,b,c List 
   
     list2 = Arrays.asList("a", "b", "c"); String result = list2.stream().collect(Collectors.joining(",")); // Collectors.joining(",")的结果是:a,b,c 然后再将结果 x + "d"操作, 最终返回a,b,cd String str= Stream.of("a", "b", "c").collect(Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d")); } 
   
元素聚合
 @Test public void test(){ // 求最值 3 List 
   
     list = Arrays.asList(1, 2, 3); Integer maxValue = list.stream().collect(Collectors.collectingAndThen(Collectors.maxBy((a, b) -> a - b), Optional::get)); // 最小值 1 Integer minValue = list.stream().collect(Collectors.collectingAndThen(Collectors.minBy((a, b) -> a - b), Optional::get)); // 求和 6 Integer sumValue = list.stream().collect(Collectors.summingInt(item -> item)); // 平均值 2.0 Double avg = list.stream().collect(Collectors.averagingDouble(x -> x)); } 
   
@Test public void test(){ // 映射:先对集合中的元素进行映射,然后再对映射的结果使用Collectors操作 // A,B,C Stream.of("a", "b", "c").collect(Collectors.mapping(x -> x.toUpperCase(), Collectors.joining(","))); } 
分组
 public class User { private Long id; private String username; private Integer type; // Getter & Setter & toString } @Test public void testGroupBy(){ List 
   
     list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 奇偶数分组:奇数分一组,偶数分一组 // groupingBy(Function 
     classifier) 参数是Function类型,Function返回值可以是要分组的条件,也可以是要分组的字段 // 返回的结果是Map,其中key的数据类型为Function体中计算类型,value是List 
    
      类型,为分组的结果 Map 
     
       > result = list.stream().collect(Collectors.groupingBy(item -> item % 2 == 0)); // {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8, 10]} System.out.println(result); // partitioningBy 用于分成两组的情况 Map 
      
        > twoPartiton = list.stream().collect(Collectors.partitioningBy(item -> item % 2 == 0)); System.out.println(twoPartiton); User user = new User(1L, "zhangsan", 1); User user2 = new User(2L, "lisi", 2); User user3 = new User(3L, "wangwu", 3); User user4 = new User(4L, "fengliu", 1); List 
       
         users = Arrays.asList(user, user2, user3, user4); // 根据某个字段进行分组 Map 
        
          > userGroup = users.stream().collect(Collectors.groupingBy(item -> item.type)); / * key 为要分组的字段 * value 分组的结果 * { * 1=[User{id=1, username='zhangsan', type=1}, User{id=4, username='fengliu', type=1}], * 2=[User{id=2, username='lisi', type=2}], * 3=[User{id=3, username='wangwu', type=3}] * } */ System.out.println(userGroup); } // 分组并对分组中的数据统计 @Test public void testGroupBy2() { Foo foo1 = new Foo(1, 2); Foo foo2 = new Foo(2, 23); Foo foo3 = new Foo(2, 6); List 
         
           list = new ArrayList<>(4); list.add(foo1); list.add(foo2); list.add(foo3); Map 
          
            collect = list.stream().collect(Collectors.groupingBy(Foo::getCode, Collectors.summarizingInt(Foo::getCount))); IntSummaryStatistics statistics1 = collect.get(1); IntSummaryStatistics statistics2 = collect.get(2); System.out.println(statistics1.getSum()); System.out.println(statistics1.getAverage()); System.out.println(statistics1.getMax()); System.out.println(statistics1.getMin()); System.out.println(statistics1.getCount()); System.out.println(statistics2.getSum()); System.out.println(statistics2.getAverage()); System.out.println(statistics2.getMax()); System.out.println(statistics2.getMin()); System.out.println(statistics2.getCount()); } 
           
          
         
        
       
      
     
   
累计操作
@Test public void testReducing(){ // sum: 是每次累计计算的结果,b是Function的结果 System.out.println(Stream.of(1, 3, 4).collect(Collectors.reducing(0, x -> x + 1, (sum, b) -> { System.out.println(sum + "-" + b); return sum + b; }))); // 下面代码是对reducing函数功能实现的描述,用于理解reducing的功能 int sum = 0; List 
   
     list3 = Arrays.asList(1, 3, 4); for (Integer item : list3) { int b = item + 1; System.out.println(sum + "-" + b); sum = sum + b; } System.out.println(sum); // 注意reducing可以用于更复杂的累计计算,加减乘除或者更复杂的操作 // result = 2 * 4 * 5 = 40 System.out.println(Stream.of(1, 3, 4).collect(Collectors.reducing(1, x -> x + 1, (result, b) -> { System.out.println(result + "-" + b); return result * b; }))); } 
   

对BigDecimal分组求和。

Map<String, BigDecimal> returnPaymentMap = retrnPayments.stream().collect(Collectors.groupingBy( Payment::getPayType, Collectors.mapping(Payment::getPayAmount, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))) ); 

分享一个朋友的人工智能教程。比较通俗易懂,风趣幽默,感兴趣的朋友可以去看看。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220696.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午7:51
下一篇 2026年3月17日 下午7:52


相关推荐

  • 常见电容器图片_电容分类图片-各种电容器图片[通俗易懂]

    常见电容器图片_电容分类图片-各种电容器图片[通俗易懂]《电容分类图片-各种电容器图片》由会员分享,可在线阅读,更多相关《电容分类图片-各种电容器图片(7页珍藏版)》请在人人文库网上搜索。1、电容分类图片-各种电容器图片第1幅图1胆电容。图2灯具电容器。图3MKPH电容。图4MET电容。图5,10PEI电容,图6,胆贴片电容。图7MPE电容。图8贴片电容。图11轴向电解电容器。图12MPP电容第2幅图1PPN电容。图2PET电容…

    2022年8月22日
    8
  • Gemini 3 的智能体(Agent)能力:从“回答问题”到“完成目标”

    Gemini 3 的智能体(Agent)能力:从“回答问题”到“完成目标”

    2026年3月16日
    3
  • 方法区元空间实现之jdk7和8字符串常量池、运行时常量池、静态变量到底在哪?

    方法区元空间实现之jdk7和8字符串常量池、运行时常量池、静态变量到底在哪?方法区(落地实现jdk7永久代,jdk8元空间),元空间并不在虚拟机中,而是使用本地内存1、此区域是线程共享的。储存已加载的类信息、常量、静态变量、即时编译器编译后的代码等数据;2、常量池:编译器生成的各种字面量和符号引用;3、关于字符串常量池和运行时常量池的位置说明:jdk1.6存在永久代,字符串常量池、运行时常量池都是在永久代中;jdk1.7存在永久代,字符串常量池被移动到了堆当中,运行时常量池还是在永久代中;jdk1.8不存在永久代,实现形式是元空间,字符串常量池仍然在堆当中,运行.

    2022年5月23日
    44
  • SQLite数据库中文乱码处理「建议收藏」

    SQLite数据库中文乱码处理「建议收藏」通过SQLiteAdministrator等工具生成的数据库文件,放入到Android中,查询记录怎么也查不出来,后来发现是编码错误,SQLiteAdministrator不支持utf编码,所以存储的中文会出现乱码的情况,处理方法如下:SQLiteDatabasedb=dbHelper.getWritableDatabase();Cursorcursor

    2025年8月26日
    7
  • css常用代码大全,html+css代码

    css常用代码大全,html+css代码css 常用代码大全 html css 代码 html css 可以很方便的进行网页的排版布局 还能减少很多不必要的代码 一 文本设置 1 font size 字号参数 nbsp 2 font style 字体格式 3 font weight 字体粗细 4 颜色属性 color 参数注意使用网页安全色二 超链接设置 text de

    2026年3月26日
    2
  • Pytest(5)美化插件进度条pytest-sugar[通俗易懂]

    Pytest(5)美化插件进度条pytest-sugar[通俗易懂]前言在我们进行自动化测试的时候,用例往往是成百上千,执行的时间是几十分钟或者是小时级别。有时,我们在调试那么多用例的时候,不知道执行到什么程度了,而pytest-sugar插件能很好解决我们的痛点。

    2022年7月30日
    9

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号