当前位置:网站首页>Lambda expression and flow optimization code
Lambda expression and flow optimization code
2022-06-12 21:47:00 【NGC73】
lambda Expression and flow optimization code
1 Code application example
java8 In the past, it was used to sort collections , For example, you need to follow a certain Time of collection Sort the sets
Collections.sort(payList, new Comparator<ErpContractPay>() {
@Override
public int compare(ErpContractPay o1, ErpContractPay o2) {
System.out.println(o1);
Date payTime1 = o1.getPayTime();
Date payTime2 = o2.getPayTime();
// Judge whether it is empty first
if(payTime1==null||payTime2==null){
throw new RuntimeException(" Empty time exists , Can't compare ");
}else{
return payTime1.compareTo(payTime2);
}
}
});
java8 Future new feature implementations , The code becomes clear , Easy to read .
private List sortPayTime(List payList) {
return payList.stream()
.sorted(comparing(ErpContractPay::getPayTime)) // Sort by payment time
.collect(Collectors.toList()); // Convert to List
}
For example, sorting the load dictionary cache
Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()){
DictUtils.setDictCache( entry.getKey(),
entry.getValue().
stream().
sorted(Comparator.comparing(SysDictData::getDictSort)).
collect(Collectors.toList()));
}
java17 New features for stream Further optimization , If necessary Stream convert to List, You need to call collect Methods use Collectors.toList(), The code is very verbose . stay Java 17 Will become simple , Can be called directly toList().
Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()){
DictUtils.setDictCache( entry.getKey(),
entry.getValue().
stream().
sorted(Comparator.comparing(SysDictData::getDictSort)).
toList();
}
2 Use of streams
The use of stream will be divided into terminal operation and intermediate operation
2.1 Intermediate operation
2.1.1 filter Screening
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().filter(i -> i > 3);
By using filter Methods the conditions were screened ,filter The method parameter of is a condition
2.1.2 distinct Remove duplicate elements
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().distinct();
adopt distinct Method quickly remove the repeated elements
2.1.3 limit Returns the specified number of streams
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().limit(3);
adopt limit Method specifies the number of return streams ,limit The parameter value of must be >=0, Otherwise, an exception will be thrown
2.1.4 skip Skip the elements in the stream
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().skip(2);
adopt skip Method to skip elements in the stream , The above example skips the first two elements , So the result is 2,3,4,5,skip The parameter value of must be >=0, Otherwise, an exception will be thrown
2.1.5 map Stream Mapping
The so-called flow mapping is to map the accepted element to another element
List stringList = Arrays.asList(“Java 8”, “Lambdas”, “In”, “Action”);
Stream stream = stringList.stream().map(String::length);
2.1.6 Copy code
adopt map Method to complete the mapping , The example is completed String -> Integer Mapping , The above example passes map The method is done Dish->String Mapping
2.1.7 flatMap Stream switching
Convert each value in one stream to another stream
List wordList = Arrays.asList(“Hello”, “World”);
List strList = wordList.stream()
.map(w -> w.split(" “))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
map(w -> w.split(” ")) The return value of is Stream<String[]>, We want to get Stream, Can pass flatMap Method to complete Stream ->Stream Transformation
2.1.8 Element match
There are three ways to match :
1.allMatch Match all
List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
System.out.println(“ It's worth more than 3”);
}
2.anyMatch Match one of them
List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().anyMatch(i -> i > 3)) {
System.out.println(“ There is more than 3 Value ”);
}
Equate to
for (Integer i : integerList) {
if (i > 3) {
System.out.println(“ There is more than 3 Value ”);
break;
}
}
3.noneMatch All don't match
List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
System.out.println(“ It's less than 3”);
}
2.2 Terminal operation
2.2.1 Count the number of elements in the stream
adopt count
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();
By using count Method to count the number of elements in the output stream
adopt counting
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());
The last way to count the number of elements is with collect It's especially useful when used in combination
2.2.2 lookup
There are two ways to find
findFirst find first
// Find first greater than 3 And print
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findFirst();
findAny Look for a random
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findAny();
adopt findAny Method to find one of the elements greater than three and print , Because of internal optimization , It ends when the first element satisfying more than three is found , The results of this method and findFirst The method gives the same result . Provide findAny Method is to make better use of parallel flow ,findFirst Methods are more limited in parallelism
2.2.3 reduce Combine the elements in the stream
Suppose we sum the values in a set
JDK8 Before :
int sum = 0;
for (int i : integerList) {
sum += i;
}
JDK8 After through reduce To deal with
int sum = integerList.stream().reduce(0, (a, b) -> (a + b));
It can be done in one line , You can also use method references to abbreviate to :
int sum = integerList.stream().reduce(0, Integer::sum);
reduce Take two parameters , An initial value here is 0, One BinaryOperator accumulator To combine the two elements to produce a new value ,
in addition , reduce Method also has an overloaded method with no initialization value
2.2.4 Get the minimum and maximum values in the stream
adopt min/max Get the minimum and maximum
Optional min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional max = menu.stream().map(Dish::getCalories).max(Integer::compareTo);
Or you could write it as :
OptionalInt min = menu.stream().mapToInt(Dish::getCalories).min();
OptionalInt max = menu.stream().mapToInt(Dish::getCalories).max();
min Get the minimum value in the stream ,max Get the maximum value in the stream , Method parameters are Comparator<? super T> comparator
adopt minBy/maxBy Get the minimum and maximum
Optional min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional max = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));
minBy Get the minimum value in the stream ,maxBy Get the maximum value in the stream , Method parameters are Comparator<? super T> comparator
adopt reduce Get the minimum and maximum
Optional min = menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optional max = menu.stream().map(Dish::getCalories).reduce(Integer::max);
Reference article :
https://libin9ioak.blog.csdn.net/article/details/122174470?spm=1001.2014.3001.5502
https://blog.csdn.net/u014231523/article/details/102535902
边栏推荐
- 如何自己动手写一个vscode插件,实现插件自由!
- 【目标检测】|Dive Deeper Into Box for Object Detection 基于FCOS新训练方法
- Recommended Chinese font in the code input box of Oracle SQL developer
- 动态规划之如何将问题抽象转化为0-1背包问题(详解利用动态规划求方案数)
- My struggle: my years in foreign enterprises (1)
- Main stages of garbage collection in ZGC
- Ansible playbook和Ansible Roles(三)
- Data batch writing
- June training (day 10) - bit operation
- 建立高可用的数据库
猜你喜欢

SQL调优指南笔记9:Joins

Smart management of green agriculture: a visual platform for agricultural product scheduling

图灵奖得主:想要在学术生涯中获得成功,需要注意哪些问题?

一款高颜值的MySQL管理工具

JUC并发工具包使用指南

Recommended Chinese font in the code input box of Oracle SQL developer

SQL调优指南笔记6:Explaining and Displaying Execution Plans

SQL调优指南笔记15:Controlling the Use of Optimizer Statistics

Cookies and sessions

SQL tuning guide notes 10:optimizer statistics concepts
随机推荐
Logstash timestamp converted to UNIX nanosecond nano second time
SQL调优指南笔记10:Optimizer Statistics Concepts
Ansible基础和常用模块(一)
如何自己动手写一个vscode插件,实现插件自由!
脱颖而出!OceanBase 入选 2021“科创中国”开源创新榜单
六月集训(第11天) —— 矩阵
Oracle LiveLabs实验:Introduction to Oracle Spatial Studio
NiO User Guide
Yyds dry goods inventory solution sword finger offer: the first non repeated character in the character stream
[QNX hypervisor 2.2 user manual] 4.3 obtain the host component
大学期间零基础如何开展编程学习
The Post-00 financial woman with a monthly salary of 2W conquered the boss with this set of report template
Recommended Chinese font in the code input box of Oracle SQL developer
Permission to query execution plan in Oracle Database
[target detection] |dive detector into box for object detection new training method based on fcos
What is the difference between a user thread and a daemon thread?
C language learning notes (II)
MySQL master-slave replication
Ansible playbook和变量(二)
SQL tuning guide notes 14:managing extended statistics