当前位置:网站首页>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);
}}边栏推荐
- The analysis, solution and development of the problem of router dropping frequently
- ARIMA model for time series analysis and prediction
- Como automatic test system: build process record
- 2022.7.22DAY612
- 总结软件测试岗的那些常见高频面试题
- MySQL之执行计划
- NFT digital collection system development: digital collections give new vitality to brands
- 从Boosting谈到LamdaMART
- Interview question set
- MMOE多目标建模
猜你喜欢

Installation of Baidu flying paste deep learning framework tutorial in Anaconda

Jmeter性能测试之使用存储响应内容到文件监听器

Dynamic performance view overview
![[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)

MySQL之执行计划

总结软件测试岗的那些常见高频面试题

【每日一题】919. 完全二叉树插入器

Comparison and difference between dependence and Association

PXE efficient batch network installation

Web page basic label
随机推荐
Regression analysis code implementation
Network Trimming: A Data-Driven Neuron Pruning Approach towards Efficient Deep Architectures论文翻译/笔记
Speech at 2021 global machine learning conference
OVS underlying implementation principle
Tensorflow learning diary tflearn
MMOE multi-objective modeling
2021全球机器学习大会演讲稿
Common templates for web development
Learning Efficient Convolutional Networks Through Network Slimming
Shardingsphere data slicing
Hcip--- BGP comprehensive experiment
OAuth2.0系列博客教程汇总
Kdd2022 | uncover the mystery of Kwai short video recommendation re ranking, and recommend the new SOTA
Network ()
Jmeter性能测试之将每次接口请求的结果保存到文件中
Simulation of transfer function step response output of botu PLC first-order lag system (SCL)
【每日一题】919. 完全二叉树插入器
NFT digital collection development: Six differences between digital collections and NFT
Practice of online question feedback module (XIV): realize online question answering function
【推荐系统经典论文(十)】阿里SDM模型