当前位置:网站首页>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
边栏推荐
- gzip压缩解压缩
- Deep Hough voting for 3D object detection in point clouds
- PE安装win10系统
- PCB package download website recommendation and detailed usage
- Simple understanding of cap and base theory
- Graphics2D类基本使用
- NIO使用指南
- 脱颖而出!OceanBase 入选 2021“科创中国”开源创新榜单
- Okio source code analysis
- 复杂系统如何检测异常?北卡UNCC等最新《复杂分布式系统中基于图的深度学习异常检测方法综述》,阐述最新图异常检测技术进展
猜你喜欢

Oracle LiveLabs实验:Introduction to Oracle Spatial Studio

复杂系统如何检测异常?北卡UNCC等最新《复杂分布式系统中基于图的深度学习异常检测方法综述》,阐述最新图异常检测技术进展

Graphics2d class basic use

SQL tuning guide notes 14:managing extended statistics

C language learning notes (II)

Cookies and sessions

利用ADG Standby克隆PDB

Kdd2022 | graphmae: self supervised mask map self encoder

Xingda easy control ModbusRTU to modbustcp gateway

SQL tuning guide notes 17:importing and exporting optimizer statistics
随机推荐
Ansible Roles-项目案例(四)
NIO使用指南
SQL tuning guide notes 10:optimizer statistics concepts
[qnx hypervisor 2.2 manuel de l'utilisateur] 4.2 environnement de construction pris en charge
Linux backup MySQL
Experiment 7-2-6 print Yanghui triangle (20 points)
C language learning notes (II)
图灵奖得主:想要在学术生涯中获得成功,需要注意哪些问题?
NPOI 创建Word
六月集训(第12天) —— 链表
Yyds dry goods inventory solution sword finger offer: the first non repeated character in the character stream
OceanBase 社区版 OCP 功能解读
2023届校园招聘正式开启!OceanBase 想和你在这个春天约一场面试
[QNX hypervisor 2.2 user manual] 4.4 build host
PCB封装下载网站推荐及其详细使用方法
利用ADG Standby克隆PDB
Npoi create word
ZGC concurrent identity and multi view address mapping in concurrent transition phase
ICML2022 | GALAXY:极化图主动学习
PE installation win10 system