当前位置: 首页 > news >正文

jdk 04 stream的collect方法

01.收集(collect)
collect,收集,可以说是内容最繁多、功能最丰富的部分了。

从字面上去理解,就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合。

collect主要依赖java.util.stream.Collectors类内置的静态方法。

这个是stream中的collect方法:

  <R, A> R collect(Collector<? super T, A, R> collector);

在这里插入图片描述

02.归集(toList/toSet/toMap)
因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。 toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。

List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());System.out.println("产生的新集合是:" + listNew);Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());System.out.println("产生的不重复的新集合是:" + set);List<Person> personList = new ArrayList<>();personList.add(new Person("Tom", 8900, 22, "male", "New Yark"));personList.add(new Person("Jack", 7000, 29, "male", "Washington"));personList.add(new Person("Lily", 7800, 24, "female", "Washington"));personList.add(new Person("Anni", 8200, 28, "female", "New Yark"));personList.add(new Person("Owen", 9500, 26, "male", "New Yark"));personList.add(new Person("Alisa", 7900, 27, "female", "New Yark"));Map<?, Person> personMap =personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName,p -> p));System.out.println("产生的新的map集合是:" + personMap);

3.统计(count/averaging)
Collectors提供了一系列用于数据统计的静态方法:

计数:count
平均值:averagingInt、averagingLong、averagingDouble
最值:maxBy、minBy
求和:summingInt、summingLong、summingDouble
统计以上所有:summarizingInt、summarizingLong、summarizingDouble
		/*** 案例:统计员工人数、平均工资、工资总额、最高工资。*/// 求总数Long count = personList.stream().collect(Collectors.counting());System.out.println("员工总数:" + count);// 求平均工资Double avgSalary = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));System.out.println("员工平均工资:" + avgSalary);// 求工资之和Integer sumSalary = personList.stream().collect(Collectors.summingInt(Person::getSalary));System.out.println("员工工资总和:" + sumSalary);// 一次性统计所有信息DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));System.out.println("员工工资所有统计:" + collect);

分组(partitioningBy/groupingBy)

分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
		/*** 案例:将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组*/// 将员工按薪资是否高于8000分组Map<Boolean, List<Person>> part =personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));// 将员工按性别分组Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));// 将员工先按性别分组,再按地区分组Map<String, Map<String, List<Person>>> group2 =personList.stream().collect(Collectors.groupingBy(Person::getSex,Collectors.groupingBy(Person::getArea)));System.out.println("员工按薪资是否大于8000分组情况:" + part);System.out.println("员工按性别分组情况:" + group);System.out.println("员工按性别、地区:" + group2);

接合(joining)
joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

	String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));System.out.println("所有员工的姓名:" + names);List<String> strs = Arrays.asList("A", "B", "C");String str = strs.stream().collect(Collectors.joining("-"));System.out.println("拼接后的字符串:" + str);

归约(reducing)
Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。

	// 每个员工减去起征点后的薪资之和Integer sumsal = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (x, y) -> x + y - 5000));System.out.println("员工扣税薪资总和:" + sumsal);// stream的reduceInteger sum = personList.stream().map(Person::getSalary).reduce(0, (x, y) -> x + y - 5000);System.out.println("----员工扣税薪资总和:" + sum);

排序(sorted)
sorted,中间操作。有两种排序:

 sorted():自然排序,流中元素需实现Comparable接口sorted(Comparator com):Comparator排序器自定义排序
/*** 案例:将员工按工资由高到低(工资一样则按年龄由大到小)排序*/
// 按工资升序排序(自然排序)
List<String> nameList =personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
System.out.println("按工资升序排序(自然排序):" + nameList);
// 按工资降序排序
List<String> nameList1 =personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());
System.out.println("按工资降序排序:" + nameList1);// 先按工资再按年龄升序排序
List<String> nameList2 =personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
System.out.println("先按工资再按年龄升序排序:" + nameList2);// 先按工资再按年龄自定义排序(降序)
List<String> nameList3 = personList.stream().sorted((p1, p2) -> {if (p1.getSalary() == p2.getSalary()) {return p2.getAge() - p1.getAge();} else {return p2.getSalary() - p1.getSalary();}
}).map(Person::getName).collect(Collectors.toList());
System.out.println("先按工资再按年龄自定义排序(降序):" + nameList3);

提取/组合
流也可以进行合并(concat)、去重(distinct)、限制(limit)、跳过(skip)等操作。

String[] arr1 = {"a", "b", "c", "d"};
String[] arr2 = {"d", "e", "f", "g"};Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);// concat:合并两个流 distinct:去重
List<String> stringList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
System.out.println("流合并:" + stringList);
// limit:限制从流中获得前n个数据
List<Integer> integerList = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
System.out.println("limit:" + integerList);
// skip:跳过前n个数据
List<Integer> integerList1 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());
System.out.println("skip:" + integerList1);
http://www.lryc.cn/news/139035.html

相关文章:

  • 介绍REST API
  • 【leetcode 力扣刷题】反转链表+递归求解
  • 一文读懂Redis配置,史上真香配置
  • maven打出jar中动态替换占位符
  • 【Git游戏】通过游戏重新学习Git
  • 如何通过以太坊JSON-RPC方式获取ERC-20代币的信息?
  • 线性代数的学习和整理4: 求逆矩阵的多种方法汇总
  • 【C#学习笔记】匿名函数和lambda表达式
  • 百度Apollo:引领自动驾驶技术创新的先锋
  • Redis 重写 AOF 日志期间,主进程可以正常处理命令吗?
  • java实现生成RSA公私钥、SHA256withRSA加密以及验证工具类
  • lab7 thread
  • 接口自动化测试:mock server之Moco工具
  • 用python从零开始做一个最简单的小说爬虫带GUI界面(2/3)
  • CEF 缓存处理:清理缓存、禁用缓存、忽略缓存
  • Android 系统桌面 App —— Launcher 开发(1)
  • 一个程序员的工作日记--每天就干两件事,一年后让别人刮目相看
  • Linux虚拟机安装(Ubuntu 20)
  • 1.6 服务器处理客户端请求
  • 火山引擎发布自研视频编解码芯片 压缩效率提升30%
  • 从头开始:将新项目上传至Git仓库的简易指南
  • 数据库的增量备份与差异备份
  • 视频云存储/安防监控视频智能分析网关V3:占道经营功能详解
  • 卡尔曼滤波学习笔记
  • NLP预训练模型超大规模探索
  • OpenCV实战系列总目录(更新中)
  • 《华为认证》6to4自动隧道
  • Java课题笔记~Element UI
  • [论文笔记]ON LAYER NORMALIZATION IN THE TRANSFORMER ARCHITECTURE
  • h5逻辑_调用手机拨号功能