当前位置:网站首页>Stream API optimization code
Stream API optimization code
2022-04-22 09:21:00 【l_ learning】
Use Java8 China new features Lambda Expressions and stream declarations handle data sets , Make the code simpler
Use a simple employee class to learn how to use
public class Employee {
/** * full name */
private String name;
/** * Age */
private int age;
/** * Salary */
private double salary;
/** * department */
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;
}
//... Omit
}
Test set ( Simulated data query data )
List<Employee> stuList = new ArrayList<>();
stuList.add(new Employee(" Xiao Ming ", 18, " Development Department ", 2000.00));
stuList.add(new Employee(" Xiaohong ", 20, " Development Department ", 2100.00));
stuList.add(new Employee(" cockroach ", 25, " Testing department ", 2200.00));
Age is less than 25 The names of employees aged are sorted by age
List<String> result = stuList.stream()
// Age less than 25 Year old employees
.filter(stu -> stu.getAge() < 25)
// Sort by age
.sorted(comparing(Employee::getAge))
// Get employee name
.map(Employee::getName)
// Convert to List
.collect(Collectors.toList());
Classify by employee Department
Map<String, List<Employee>> deptEmployee = stuList.stream()
.collect(groupingBy(Employee::getDept));
filter The method parameter of is a condition ,filter The screening age is greater than 25 Year old employees
List<Employee> employeeFilter = stuList.stream()
.filter(i -> i.getAge() > 25)
.collect(toList());
distinct Remove duplicate elements ( Cannot duplicate according to the content of object attribute )
List<Employee> employeeDistinct = stuList.stream()
.distinct()
.collect(toList());
limit Returns the specified number of streams ,limit The parameter value of must be >=0
List<Employee> employeeLimit = stuList.stream()
.limit(3)
.collect(toList());
skip Skip the elements in the stream ,skip The parameter value of must be >=0, Start with the third element
List<Employee> employeeSkip = stuList.stream()
.skip(2)
.collect(toList());
map Method is similar to an iterator , Gets the Department in the collection
List<String> dept = stuList.stream()
.map(i->i.getDept())
.collect(Collectors.toList());
flatMap Stream switching , Get the Department in the employee list , Those with multiple departments are separated by commas and de duplicated
List<String> deptDistinct = stuList.stream()
.map(w -> w.getDept().split(","))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
Get the minimum age of the employee
Optional<Integer> min = stuList.stream()
.map(Employee::getAge)
.min(Integer::compareTo);
Get the minimum age of the employee
OptionalInt min2 = stuList.stream()
.mapToInt(Employee::getAge)
.min();
Get the maximum employee age
Optional<Integer> max = stuList.stream()
.map(Employee::getAge)
.max(Integer::compareTo);
Get the maximum employee age
OptionalInt max2 = stuList.stream()
.mapToInt(Employee::getAge)
.max();
minBy Get the minimum age of the employee
Optional<Integer> minBy = stuList.stream()
.map(Employee::getAge)
.collect(minBy(Integer::compareTo));
maxBy Get the maximum employee age
Optional<Integer> maxBy = stuList.stream()
.map(Employee::getAge)
.collect(maxBy(Integer::compareTo));
reduce Get the maximum employee age
Optional<Integer> reduceMin = stuList.stream()
.map(Employee::getAge)
.reduce(Integer::min);
reduce Get the maximum employee age
Optional<Integer> reduceMax = stuList.stream()
.map(Employee::getAge)
.reduce(Integer::max);
Sum up , The sum of employees' salaries
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 Find the average age of employees
double average = stuList.stream()
.collect(averagingInt(Employee::getAge));
summarizingInt At the same time, calculate the total salary of employees 、 Average 、 Maximum 、 minimum value
DoubleSummaryStatistics doubleSummaryStatistics = stuList.stream()
.collect(summarizingDouble(Employee::getSalary));
// Get average
double summarizingDoubleAverage = doubleSummaryStatistics.getAverage();
// Get the minimum
double summarizingDoubleMin = doubleSummaryStatistics.getMin();
// Get the maximum
double summarizingDoubleMax = doubleSummaryStatistics.getMax();
// Get the sum
double summarizingDoubleSum = doubleSummaryStatistics.getSum();
Return employee name List aggregate
List<String> nameList = stuList.stream()
.map(Employee::getName)
.collect(toList());
Return employee name Set aggregate
Set<String> nameSet = stuList.stream()
.map(Employee::getName)
.collect(toSet());
adopt joining Concatenate employee names with commas
String joinName = stuList.stream()
.map(Employee::getName)
.collect(joining(", "));
adopt groupingBy Group employee departments
Map<String, List<Employee>> deptGroup = stuList.stream()
.collect(groupingBy(Employee::getDept));
allMatch Match all , Employees are older than 60
boolean allMatch = stuList.stream()
.allMatch(i -> i.getAge() > 60);
anyMatch Match one of them , There are employees older than 60 The employees'
boolean anyMatch = stuList.stream()
.anyMatch(i -> i.getAge() > 60);
noneMatch All don't match , Employees are younger than 60
boolean noneMatch = stuList.stream()
.noneMatch(i -> i.getAge() > 60);
adopt count Count the number of employees
Long count = stuList.stream()
.count();
adopt counting Count the number of employees
Long counting = stuList.stream()
.collect(counting());
findFirst Look for ages greater than 60 Year old first employee
Optional<Employee> findFirst = stuList.stream()
.filter(i -> i.getAge() > 60)
.findFirst();
findAny Randomly find a person older than 60 Year old first employee
Optional<Employee> resultFindAny = stuList.stream()
.filter(i -> i.getAge() > 60)
.findAny();
partitioningBy partition , Yes, older than 60 The sum of is less than or equal to 60 The partition
Map<Boolean, List<Employee>> partitioningBy = stuList.stream()
.collect(partitioningBy(i -> i.getAge() > 60));
Sum the values in a set
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
// Sum the values in a set
int integerListSum = integerList.stream()
.reduce(0, (a, b) -> (a + b));
// Sum the values in a set
int integerListSum2 = integerList.stream()
.reduce(0, Integer::sum);
foreach Do element traversal
stuList.stream().forEach(System.out::println);
版权声明
本文为[l_ learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220848516080.html
边栏推荐
- 宝宝起名神器小程序源码_支持多种流量主模式
- Merge two ordered linked lists (iteration)
- mysql C语言连接
- 2022 high voltage electrician test simulation 100 questions and answers
- onenet云平台数据推送到数据库
- 云原生微服务的下一站 微服务引擎 MSE 升级
- 【ValueError: math domain error】
- 新书推荐——IPv6技术与应用(锐捷版)
- oracle18c rac安装grid执行脚本root.sh报错,PRCR-1013 : 无法启动资源 ora.ons
- Shrimp noodles: what is zero copy? How to achieve zero copy?
猜你喜欢
随机推荐
VMware 虚拟机安装 OpenWrt 作旁路由 单臂路由 img 镜像转 vmdk
There is no product yet. Musk's "boring company" is valued at $5.7 billion
分隔链表(建两个空链表)
Shrimp noodles: what is zero copy? How to achieve zero copy?
Six methods can make you gain more in NFT trading
Halo 开源项目学习(一):项目启动
多线程技术核心
OJ每日一练——完数
[path of system analyst] real topic of case analysis of system analyst in 2020
Construire manuellement le tissu hyperledger V2. X réseau de production (IV) Création de canaux, cycle de vie des codes de chaîne
解读智慧农业未来发展
单片机开发之裸机也能 “多任务”?
电脑拆机清灰及机械硬盘安装记录
知识点的5W
Palindrome linked list (copy linked list to array, speed pointer + reverse linked list)
【图像隐写】Fixed Neural Network Steganography: Train the images, not the network 整理
The penultimate node in the linked list (sequential search, speed pointer)
C#导入详细内容
云原生架构下的微服务选型和演进
Selection and evolution of microservices under cloud native architecture









