当前位置:网站首页>Lambda and stream
Lambda and stream
2022-07-26 07:36:00 【Mourning】
lambda
1. The reason for this : In order to adapt to the trend of the times , Only the continuous progress of language , Can not be eliminated by the world ,java1.8 There is lambda,Lambda The expression is an anonymous function , We can lambda The expression is understood as a paragraph Code that can be passed ( Pass code snippets like data ). Use it to write more concise , More flexible code . As a more compact style of code , send java The language ability of .Lambda The essence of expression is just a “ Grammatical sugar ”, Infer from the compiler and help you transform the wrapper into regular code , So you can use less code to do the same thing .
list.sort(new Comparator<User>() {
@Override
public int compare(User o1, User o2)
{ return o1.getId()-o2.getId(); } }While using lambda in the future , We can write this way
list.sort((User o1, User o2)-> { return o1.getId()-o2.getId(); });One line of code can end , Is it more efficient than before , This is it. java The charm of language .
2.lambda Structure of expression :
- Lambda Expressions can have zero , One or more parameters .
- You can explicitly declare the type of the parameter , The compiler can also automatically infer the type of parameters from the context . for example (int a,int b) And (a,b) identical .
- Parameters are enclosed in parentheses , Separate with commas . for example (a, b) or (int a, int b) or (String a, int b, float c).
- Empty parentheses are used to indicate a set of empty parameters . for example () -> 42.
- When there is only one parameter , If you don't explicitly indicate the type , You do not need to use parentheses, such as a -> return a*a.
- Lambda The body of an expression can contain zero , One or more statements .
- If Lambda The body of an expression has only one statement , You don't need to write in braces , And the return value type of the expression should be the same as that of the anonymous function .
- If Lambda The body of an expression has more than one statement that must be enclosed in braces ( Code block ) in , And the return value type of the expression should be the same as that of the anonymous function .
Be careful :( Parameters )->{ Method body } Only one abstract method is allowed when a function exists .
java It's an object-oriented language , The parameter passed to the method cannot be a single function ,sort Need a comparison function , Only one object can be created , Wrap the method in an object and pass , You can create anonymous inner class objects , Wrap the comparison function ,java1.8 Then simplify the grammar again , Introduction lambda Language .
3.lambda Characteristics of :
- lambda Functions are anonymous : Anonymous functions , Generally speaking, it is a function without a name .lambda Function has no name .
- lambda Functions have inputs and outputs : Input is passed into the parameter list argument_list Value , Output is based on expression expression Calculated value .
- lambda Functions are generally simple : A single expression To determine the lambda Functions cannot complete complex logic , Can only complete very simple functions . Because the functions it realizes are clear at a glance , You don't even need a special name to explain .
Stream
- Advanced iterators when traversing collections
- yes java1.8 New features launched , And IO Completely different
- It provides various methods of operating object data sets , Statement
2. Get stream :
List<String> list = new ArrayList<>();Stream<String> stream = list.stream();
Integer[] nums = new Integer[10];Stream<Integer> stream = Arrays.stream(nums);
Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
Use BufferedReader.lines() Method , Turn each line into a stream
BufferedReader reader=new BufferedReader(new FileReader("stream.txt"));Stream<String> lineStream = reader.lines();
3. Flow operation
List<Apple> apples = applestore.stream() Access flow.filter(a -> a.getColor().equals("red")) Intermediate operation.collect(Collectors.toList()); Terminal operation
data source => Intermediate operation => Terminal operation => result
| Method name | effect |
filter() | Filter some elements in the stream , |
sorted() | Natural ordering , Elements in the stream need to implement Comparable Interface |
distinct() | Remove duplicate elements |
limit(n) | obtain n Elements |
skip(n) | skip n Elements , coordination limit(n) Paging possible |
map(): | Map it to a new element |
| Method name | effect |
forEach | Traverse the elements in the flow |
toArray | Pour the elements in the stream into an array |
min | Returns the minimum value of the element in the stream |
| max | Returns the maximum value of the element in the stream |
count | : Returns the total number of elements in the stream |
reduce | Sum all the elements |
anyMatch | Receive one Predicate function , As long as one of the elements in the flow satisfies the condition, it returns return true, Otherwise return to false |
allMatch | Receive one Predicate function , When each element in the flow meets the conditions, it returns return true, Otherwise return to false |
findFirst | Returns the first element in the stream |
collect | Pour the elements in the stream into a collection ,Collection or Map |
public static void main(String[] args) {
Car car1 = new Car(001, " BMW 1", " Red ");
Car car2 = new Car(002, " BMW 2", " black ");
Car car3 = new Car(003, " BMW 3", " white ");
Car car4 = new Car(004, " BMW 4", " Blue ");
Car car5 = new Car(002, " BMW 2", " black ");
Car[] cars = {car1, car2, car3, car4, car5};// Create a Car Array
Collection listcar= Arrays.stream(cars)// Convert to stream
.distinct()// duplicate removal
.filter((e)->{return e.getColor().equals(" Red ");})// Sifting element
.collect(Collectors.toList());//: Pour the elements in the stream into a collection ,Collection or Map
System.out.println(listcar);// For the output
// Integer [] a={1,5,9,6,3,2,4,7,8};
// Integer a1= Arrays.stream(a)
// .sorted((b,c)->{return b-c;})
// .reduce((c,b)->{return b+c;})// Sum up
// .get();
// System.out.println(a1);
// Integer [] a={1,5,9,6,3,2,4,7,8};
// Boolean a1= Arrays.stream(a)
// .sorted((b,c)->{return b-c;})
// .allMatch((e)->{return e<9;});//: Receive one Predicate function , When each element in the flow meets the conditions, it returns return true, Otherwise return to false
// System.out.println(a1);
// Integer [] a={1,5,9,6,3,2,4,7,8};
// Boolean a1= Arrays.stream(a)
// .sorted((b,c)->{return b-c;})
// .anyMatch((e)->{return e<9;});// Receive one Predicate function , As long as one of the elements in the flow satisfies the condition, it returns return true, Otherwise return to false
// System.out.println(a1);
//
// Integer [] a={1,5,9,6,3,2,4,7,8};
// long a1= Arrays.stream(a)
// .sorted((b,c)->{return b-c;})
// .count();
// System.out.println(a1);
// Integer [] a={1,5,9,6,3,2,4,7,8};
// Object [] a1= Arrays.stream(a)
// .sorted((b,c)->{return b-c;})
// .toArray();
// System.out.println(Arrays.toString(a1));
// Integer [] a={1,5,9,6,3,2,4,7,8};
// Integer a1= Arrays.stream(a)
// .sorted((b,c)->{return b-c;})
// .max((c,b)->{return c-b;})
// .get();
// System.out.println(a1);
}}边栏推荐
- NFT digital collection system development: activating digital cultural heritage
- :app:checkDebugAarMetadata 2 issues were found when checking AAR metadata: 2 issues were found when
- 2021全球机器学习大会演讲稿
- 元宇宙基础设施:WEB 3.0 chain33 优势分析
- DADNN: Multi-Scene CTR Prediction via Domain-Aware Deep Neural Network
- Oauth2.0 series blog tutorial summary
- Redis系列之什么是布隆过滤器?
- tensorflow2.x中的量化感知训练以及tflite的x86端测评
- WCF deployed on IIS
- 爬虫->TpImgspider
猜你喜欢

Dynamic performance view overview

如何保证缓存和数据库的双写一致性?

PXE高效批量网络装机

DCN (deep cross network) Trilogy

动态性能视图概述

Open source management system based on ThinkPHP

NFT digital collection system development: activating digital cultural heritage
![[C language] do you really know printf? (printf is typically error prone, and collection is strongly recommended)](/img/59/cf43b7dd16c203b4f31c1591615955.jpg)
[C language] do you really know printf? (printf is typically error prone, and collection is strongly recommended)

Simulation of transfer function step response output of botu PLC first-order lag system (SCL)

DADNN: Multi-Scene CTR Prediction via Domain-Aware Deep Neural Network
随机推荐
2022.7.22DAY612
Learning Efficient Convolutional Networks Through Network Slimming
Examples of financial tasks: real-time and offline approval of three scenarios and five optimizations of Apache dolphin scheduler in Xinwang bank
Hystrix配置简单说明
PostgreSQL UUID fuzzy search UUID string type conversion SQL error [42883] explicit type casts
现在开发人员都开始做测试了,是不是以后就没有软件测试人员了?
dcn(deep cross network)三部曲
JMeter performance test saves the results of each interface request to a file
WCF introductory tutorial II
Hcip--- BGP comprehensive experiment
“尝鲜”元宇宙,周杰伦最佳拍档方文山将于7月25日官宣《华流元宇宙》
In July, glassnode data showed that the open position of eth perpetual futures contract on deribit had just reached a one month high of $237959827.
系统架构&微服务
NFT digital collection development: digital collections help enterprise development
微服务feign调用时候,token丢失问题解决方案
DADNN: Multi-Scene CTR Prediction via Domain-Aware Deep Neural Network
程序环境和预处理
Anaconda 中安装 百度飞浆Paddle 深度学习框架 教程
3.0.0 alpha blockbuster release! Nine new functions and new UI unlock new capabilities of dispatching system
以太网交换安全