当前位置:网站首页>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
边栏推荐
- VagrantBox重新安装vboxsf驱动
- Icml2022 | Galaxy: apprentissage actif des cartes de polarisation
- 建立高可用的数据库
- drf 接收嵌套数据并创建对象, 解决:drf NOT NULL constraint failed
- Can tonghuashun open an account? Can the security of securities companies be directly opened on the app? How to open an account for securities accounts
- 【QNX Hypervisor 2.2 用户手册】4.2 支持的构建环境
- MySQL architecture and basic management (II)
- What is your understanding of thread priority?
- Graphics2d class basic use
- [QNX hypervisor 2.2 user manual] 4.3 obtain the host component
猜你喜欢

Shell script Basics

SQL tuning guide notes 14:managing extended statistics

Digital intelligence data depth | Bi goes down the altar? It's not that the market has declined, it's that the story has changed

Kdd2022 | graphmae: self supervised mask map self encoder

SQL调优指南笔记18:Analyzing Statistics Using Optimizer Statistics Advisor

Cloning PDB with ADG standby

Ansible playbook and ansible roles (III)

SQL tuning guide notes 16:managing historical optimizer statistics

How to write a vscode plug-in by yourself to realize plug-in freedom!
![[target detection] |dive detector into box for object detection new training method based on fcos](/img/ac/c54c2733dceffea086b772f35f128a.png)
[target detection] |dive detector into box for object detection new training method based on fcos
随机推荐
Ansible基础和常用模块(一)
How to write a vscode plug-in by yourself to realize plug-in freedom!
利用ADG Standby克隆PDB
MySQL introduction and installation (I)
SQL调优指南笔记13:Gathering Optimizer Statistics
Redis cluster mget optimization
在同花顺开户证券安全吗,证券开户怎么开户流程
Ansible playbook和Ansible Roles(三)
selenium操作元素遇到的异常
Turing prize winner: what should I pay attention to if I want to succeed in my academic career?
Digraph deep copy
Graphics2D类基本使用
A puzzle about + =
June training (day 10) - bit operation
Logstash timestamp converted to UNIX nanosecond nano second time
Permission to query execution plan in Oracle Database
linux备份mysql
动态规划之如何将问题抽象转化为0-1背包问题(详解利用动态规划求方案数)
Icml2022 | galaxy: active learning of polarization map
Ansible playbook和变量(二)