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

Stream强化

使用stream求list的对象属性的和

假设有一个Student类,其中有一个属性是score,可以通过以下代码求出List<Student>中score的和:

List<Student> students = new ArrayList<>(); // 添加学生对象到List中 
int sum = students.stream().mapToInt(Student::getScore).sum();

这里使用了mapToInt方法将每个Student对象映射成其score属性的值,然后调用sum方法求和。

stream返回一个map集合

可以使用以下代码将List<Student>转化为Map<String, Integer>:

Map<String, Integer> nameScoreMap = students.stream() .collect(Collectors.toMap(Student::getName, Student::getScore));

这里使用了Collectors.toMap方法将List转化为Map,其中getName方法返回Student的名字,getScore方法返回Student的score属性值。

stream添加list的对象

List<Student> students = Stream.of(
        new Student("Tom", 80),
        new Student("Mary", 90),
        new Student("John", 75))
        .collect(Collectors.toList());
这里使用了Stream.of方法创建一个流,其中包含三个新建的Student对象,然后调用collect方法将流转化为List<Student>。

stream排序

//正序排列slist=list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
//倒序排列
list = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());

按自然升序对集合进行排序

list.stream().sorted();

自然序降序使用Comparator提供reverseOrder()方法

list.stream().sorted(Comparator.reverseOrder());

还可以使用Java8的lambda表达式和Comparator接口来实现这个排序功能,代码如下:Collections.sort(openTimeList, Comparator.comparing(o -> o.getWorkDay()));这段代码使用了Comparator.comparing方法来创建一个Comparator对象,主要是根据OpenTime对象的workDay属性来进行排序,通过lambda表达式o -> o.getWorkDay()来指定workDay属性的取值方式,最后调用Collections.sort方法来进行排序。

http://www.lryc.cn/news/89896.html

相关文章:

  • 第一部分-基础篇-第一章:PSTN与VOIP(下篇)
  • 《汇编语言》- 读书笔记 - 第4章-第一个程序
  • AI工具 ChatGPT-4 vs Google Bard , PostgreSQL 开发者会pick谁?
  • 【网络】基础知识1
  • chatgpt赋能python:Python倒序range的完整指南
  • 工作笔记!
  • java设计模式之享元设计模式的前世今生
  • RESTful:理解REST架构风格、RESTful API
  • 网络面试题:什么是 TCP/IP?
  • 毫米波雷达模块在自动驾驶系统中的关键功能
  • 关于开发中对端口(port)的几点理解
  • qt 5.14.2 arm 交叉环境搭建过程
  • apt remove purge的区别 删除包的同时删除配置文件
  • 电商|跨境电商如何选择API接口和ERP
  • 测试人员的启蒙指南
  • Linux工具:vim常用快捷键
  • TA-lib第三方库安装问题
  • 接口测试的测试要点
  • 直流电机 PID 控制系统仿真研究(Simulink实现)
  • 第三章 向量与线性方程组
  • 数组题目总结 -- 花式遍历
  • Android 12.0开机过滤部分通知声音(莫名其妙的通知声音)
  • LeetCode-0525
  • 【Linux 】scp命令
  • Docker部署yolov5
  • 如何在 Axios 中去控制 Loading?大有学问!
  • 充电桩检测设备厂家TK4860C交流充电桩检定装置
  • 一文3000字实现基于Selenium+Python的web自动化测试框架
  • Android 12系统源码_窗口管理(二)WindowManager对窗口的管理过程
  • python3.8,torch1.10.2+cu113、torch-geometric 安装