当前位置:网站首页>Stream API 优化代码
Stream API 优化代码
2022-04-22 08:49:00 【l_learning】
使用Java8中新特性Lambda表达式和流申明式处理数据集合,让代码更简洁
使用一个简单的员工类来学习使用方法
public class Employee {
/** * 姓名 */
private String name;
/** * 年龄 */
private int age;
/** * 薪资 */
private double salary;
/** * 部门 */
private String dept;
public Employee(String name, int age, String dept, double salary) {
this.name = name;
this.age = age;
this.dept = dept;
this.salary = salary;
}
//...省略
}
测试集合(模拟数据查询出来的数据)
List<Employee> stuList = new ArrayList<>();
stuList.add(new Employee("小明", 18, "开发部", 2000.00));
stuList.add(new Employee("小红", 20, "开发部", 2100.00));
stuList.add(new Employee("小强", 25, "测试部", 2200.00));
年龄小于25岁的员工姓名按年龄排序
List<String> result = stuList.stream()
//筛选出年龄小于25岁的员工
.filter(stu -> stu.getAge() < 25)
//根据年龄进行排序
.sorted(comparing(Employee::getAge))
//获取员工姓名
.map(Employee::getName)
//转换为List
.collect(Collectors.toList());
按员工部门进行分类
Map<String, List<Employee>> deptEmployee = stuList.stream()
.collect(groupingBy(Employee::getDept));
filter的方法参数为一个条件,filter筛选年龄大于25岁的员工
List<Employee> employeeFilter = stuList.stream()
.filter(i -> i.getAge() > 25)
.collect(toList());
distinct去除重复元素(不能根据对象属性内容去重)
List<Employee> employeeDistinct = stuList.stream()
.distinct()
.collect(toList());
limit返回指定流个数,limit的参数值必须>=0
List<Employee> employeeLimit = stuList.stream()
.limit(3)
.collect(toList());
skip跳过流中的元素,skip的参数值必须>=0,从第三个元素开始取值
List<Employee> employeeSkip = stuList.stream()
.skip(2)
.collect(toList());
map方法类似一个迭代器,获取集合中的部门
List<String> dept = stuList.stream()
.map(i->i.getDept())
.collect(Collectors.toList());
flatMap流转换, 获取员工列表中部门,有多个部门的按逗号分割并去重
List<String> deptDistinct = stuList.stream()
.map(w -> w.getDept().split(","))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
获取员工年龄中最小值
Optional<Integer> min = stuList.stream()
.map(Employee::getAge)
.min(Integer::compareTo);
获取员工年龄中最小值
OptionalInt min2 = stuList.stream()
.mapToInt(Employee::getAge)
.min();
获取员工年龄中最大值
Optional<Integer> max = stuList.stream()
.map(Employee::getAge)
.max(Integer::compareTo);
获取员工年龄中最大值
OptionalInt max2 = stuList.stream()
.mapToInt(Employee::getAge)
.max();
minBy获取员工年龄最小值
Optional<Integer> minBy = stuList.stream()
.map(Employee::getAge)
.collect(minBy(Integer::compareTo));
maxBy获取员工年龄最大值
Optional<Integer> maxBy = stuList.stream()
.map(Employee::getAge)
.collect(maxBy(Integer::compareTo));
reduce获取获取员工年龄最大值
Optional<Integer> reduceMin = stuList.stream()
.map(Employee::getAge)
.reduce(Integer::min);
reduce获取获取员工年龄最大值
Optional<Integer> reduceMax = stuList.stream()
.map(Employee::getAge)
.reduce(Integer::max);
求和, 员工的薪资之和
double sum = stuList.stream()
.collect(summingDouble(Employee::getSalary));
double sum2 = stuList.stream()
.map(Employee::getSalary)
.reduce(0.00, Double::sum);
double sum3 = stuList.stream()
.mapToDouble(Employee::getSalary)
.sum();
averagingInt求员工年龄平均值
double average = stuList.stream()
.collect(averagingInt(Employee::getAge));
summarizingInt同时求员工薪资总和、平均值、最大值、最小值
DoubleSummaryStatistics doubleSummaryStatistics = stuList.stream()
.collect(summarizingDouble(Employee::getSalary));
//获取平均值
double summarizingDoubleAverage = doubleSummaryStatistics.getAverage();
//获取最小值
double summarizingDoubleMin = doubleSummaryStatistics.getMin();
//获取最大值
double summarizingDoubleMax = doubleSummaryStatistics.getMax();
//获取总和
double summarizingDoubleSum = doubleSummaryStatistics.getSum();
返回员工姓名List集合
List<String> nameList = stuList.stream()
.map(Employee::getName)
.collect(toList());
返回员工姓名Set集合
Set<String> nameSet = stuList.stream()
.map(Employee::getName)
.collect(toSet());
通过joining用逗号拼接员工姓名
String joinName = stuList.stream()
.map(Employee::getName)
.collect(joining(", "));
通过groupingBy进行员工部门分组
Map<String, List<Employee>> deptGroup = stuList.stream()
.collect(groupingBy(Employee::getDept));
allMatch匹配所有,员工年龄都大于60
boolean allMatch = stuList.stream()
.allMatch(i -> i.getAge() > 60);
anyMatch匹配其中一个,存在员工年龄大于60的员工
boolean anyMatch = stuList.stream()
.anyMatch(i -> i.getAge() > 60);
noneMatch全部不匹配,员工年龄都小于60
boolean noneMatch = stuList.stream()
.noneMatch(i -> i.getAge() > 60);
通过count统计员工个数
Long count = stuList.stream()
.count();
通过counting统计员工个数
Long counting = stuList.stream()
.collect(counting());
findFirst查找年龄大于60岁的第一个员工
Optional<Employee> findFirst = stuList.stream()
.filter(i -> i.getAge() > 60)
.findFirst();
findAny随机查找一个年龄大于60岁的第一个员工
Optional<Employee> resultFindAny = stuList.stream()
.filter(i -> i.getAge() > 60)
.findAny();
partitioningBy进行分区, 对年龄大于60的与小于等于60的分区
Map<Boolean, List<Employee>> partitioningBy = stuList.stream()
.collect(partitioningBy(i -> i.getAge() > 60));
对一个集合中的值进行求和
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
//对一个集合中的值进行求和
int integerListSum = integerList.stream()
.reduce(0, (a, b) -> (a + b));
//对一个集合中的值进行求和
int integerListSum2 = integerList.stream()
.reduce(0, Integer::sum);
foreach进行元素遍历
stuList.stream().forEach(System.out::println);
版权声明
本文为[l_learning]所创,转载请带上原文链接,感谢
https://blog.csdn.net/l_learning/article/details/124312875
边栏推荐
- Mycms self media CMS system v3 2.2. Advertisement plug-in optimization
- 找工作、写简历到面试,这套资料就够了!
- The request client is not a secure context and the resource is in more-private address ...
- Advanced view of MySQL
- Servlet模版引擎使用示例
- 14 py games source code sharing
- EventBridge 集成云服务实践
- web 学习记录(中)
- 第一节:人像精修第一步-合理转档
- 2022年R1快开门式压力容器操作练习题及在线模拟考试
猜你喜欢

ERP 集成对公司系统完善的重要性

Halo 开源项目学习(一):项目启动

mysql C语言连接

玩转Kubernetes—基础概念篇

Raspberry pie Kali system HDMI modifies screen resolution

mysql用source命令导入sql出现报错 觉得应该是编码问题 不知道该怎么解决

EventBridge 集成云服务实践

2022 high altitude installation, maintenance and demolition of special operation permit examination question bank and simulated examination platform operation

Open source, not just coding

如何构建一个可“持续演进”的可观测体系?| QCon
随机推荐
学习RHCSA的第四天
vector常见接口的用法
MyCms 自媒体 CMS 系统 v3.2.2,广告插件优化
VMware 虚拟机安装 OpenWrt 作旁路由 单臂路由 img 镜像转 vmdk
【建议收藏】吐血整理Golang面试干货21问-吊打面试官-1
2022 high voltage electrician test simulation 100 questions and answers
Leetcode0396. Rotation function (medium, iteration)
Numpy notes (vstack, random.permutation, empty_like, empty, diff, random.choice, random.random, ISIN)
【图像隐写】Fixed Neural Network Steganography: Train the images, not the network 整理
2022 R1 quick opening pressure vessel operation exercises and online simulation examination
[image steganography] fixed neural network steganography: train the images, not the network
Neo4j:Merge【不存在则创建,已存在可修改】
The penultimate node in the linked list (sequential search, speed pointer)
ERP 集成对公司系统完善的重要性
jdbc连不上mysql 报错为 Access denied for user 'root'@'***' (using password: YES)
解读智慧农业未来发展
1215_SCons使用之hello world
精彩回顾|「源」来如此 第六期 - 开源经济与产业投资
Separate linked list (create two empty linked lists)
(cvpr-2014) deep learning face representation by predicting 10000 categories