当前位置:网站首页>Lambda&Stream
Lambda&Stream
2022-07-25 00:04:00 【Mr. Rabbit.】
One 、lambda
Lambda The expression is an anonymous function
The essence is just a " Grammatical sugar "
Usually use (argument) -> {body}
Can have zero
One or more parameters
You want to pass some functions to a method before , Always write anonymous classes
Grammatical sugar : A grammar added to a computer language , This grammar has no effect on the function of language , But it's easier for programmers to use . Generally speaking, the use of syntactic sugar can increase the readability of programs , So as to reduce the chance of program code error
No parameter , No return value ,lambda When there is only one line of code in the body ,{} You can ignore
() -> System.out.println(“Hello World”);
No parameter , There is a return value () -> { return 3.1415 };
With parameters , No return value (String s) -> { System.out.println(s); }
There is a parameter , No return value s -> { System.out.println(s); }
There are multiple parameters , There is a return value (int a, int b) -> { return a + b; }
There are multiple parameters , The expression parameter type can not be written ,jvm Type inference can be made according to the context (a, b) -> { return a - b; }
list.sort(new Comparator() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}) ;
/*
lambda Pass an anonymous function as a parameter
*/
list.sort((o1, o2) -> {
return o1.compareTo(o2);
});
System.out.println(list);
When there is only one parameter , If you don't explicitly indicate the type , You don't have to use braces .
for example 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 expression The return value type of the function must be the same as that of the anonymous function .
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(“Hello world”);
}
}).start();
// lambda Expression method
new Thread(
() -> System.out.println(“Hello world”)
).start();
list.forEach(new Consumer() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
// lambda Expression method
list.forEach((e)->{ System.out.println(e); });
JButton bt = new JButton();
bt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(“hello world”);
}
});
//lambda Expression method
bt.addActionListener((e)->{
System.out.println(“Hello world”);
});
List list = Arrays.asList(1,2,3,4,5,6,7) ;
for (Integer n :list){
System.out.println(n);
}
// Use Lambda expression
list.forEach((n)-> System.out.println(n));
The function interface (Functional interface)
namely @FunctionalInterface, When your annotated interface violates Functional Interface Contract time , It can be used for compiler level errors .
Find it on the ground floor @FunctionalInterface
Two 、stream
From a source that supports data processing operations , The resulting sequence of elements
flow (Stream) Many pairs of sets can be provided , Array traversal method Get stream Flow operation
// Get the stream from the collection Collections are data sources ( Do not operate on the data source )
// Store the data in the collection in Stream In the object , Yes Stream Data operations in
ArrayList list = new ArrayList<>();
Stream stream = list.stream();
// Array get stream
Integer [] a = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(a);
// Use Arrays Medium stream() Method , Convert array to stream
Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6,7);// Stream Static methods in :of()
stream2 // Direct convection operation
.filter((e)->{return e>3;})
.forEach((e1->{
System.out.println(e1);
}));
List<Integer> alist = stream2
.filter((e)->{return e>3;})
.collect(Collectors.toList());
System.out.println(alist);
Flow operation
data source => Intermediate operation => Terminal operation => result
Intermediate operation
Stream list1 = list.stream() // Convert a collection into a stream
.sorted() // Natural ordering , Elements in the stream need to implement Comparable Interface
.filter((e)->{return e>3;}) // Filter some elements in the stream
.distinct() // Remove duplicate elements
.limit(2) // obtain n Elements
.skip(2) ; // skip n Elements , coordination limit (n) Paging possible
Terminal operation
Integer list1 = list.stream()
.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
.get();
give an example
Construct an apple class , Including apple price , Color , size
public class StreamDome4 {
public static void main(String[] args) {
ArrayList<Apple> list = new ArrayList<>();
Apple apple1 = new Apple(100," red ","200");
Apple apple2 = new Apple(101," blue ","500");
Apple apple3 = new Apple(103," red ","200");
Apple apple4 = new Apple(102," red ","600");
Apple apple5 = new Apple(105," yellow ","200");
Apple apple6 = new Apple(106," red ","800");
list.add(apple1);
list.add(apple2);
list.add(apple3);
list.add(apple4);
list.add(apple5);
list.add(apple6);
/*list.stream()// Output red apples
.filter((a)->{return a.getColor().equals(" red ");})
.forEach((e)-> System.out.println(e));
*/
//map(); Map it to a new element Send out the mapped column
/*list.stream()
.map(Apple::getColor) // Traverse the color of the apple
.forEach((e)-> System.out.println(e));*/
List<String> apples = list.stream()
.filter((e)->{return e.getNum()>102;})
.map(Apple::getColor)
.collect(Collectors.toList()); // Convert streams into collections
/* Set<Apple> apples = list.stream()
.filter((e)->{return e.getNum()>102;})
.collect(Collectors.toSet());
// Convert streams into collections , Finally, output in the form of set
*/
/* Map<Integer,String> apples = list.stream()
.collect(Collectors.toMap(Apple::getNum,Apple::getColor));
*/
System.out.println(apples);
// System.out.println(list);
}
}
class Apple{
@Override
public String toString() {
return “Apple{” +
“num=” + num +
“, color='” + color + ‘’’ + //toString() Rewrite the output format
“, size='” + size + ‘’’ +
‘}’;
}
Integer num;
String color;
String size;
public Apple(int num, String color, String size){
this.num = num;
this.color = color;
this.size = size;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getNum() {
return num;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void setSize(String size) {
this.size = size;
}
public String getSize() {
return size;
}
}
边栏推荐
- [leetcode weekly replay] 303rd weekly 20220724
- Architecture design of multi live shopping mall
- Sql文件导入数据库-保姆级教程
- 指针与数组
- [brother hero July training] day 20: search Binary Tree
- Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
- 剖析kubernetes集群内部DNS解析原理
- Palm package manager of kubernetes learning offline installation of NFS client provider
- Wechat applet development learning 5 (custom components)
- Only by learning these JMeter plug-ins can we design complex performance test scenarios
猜你喜欢

91. (leaflet chapter) leaflet situation plotting - offensive direction drawing

你还在使用System.currentTimeMillis()?来看看StopWatch吧

Bug summary

Only by learning these JMeter plug-ins can we design complex performance test scenarios

The new version of SSM video tutorial in shangsilicon valley was released

Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge

Internal network mapping port to external network

Notes of Teacher Li Hongyi's 2020 in-depth learning series 9

ROS机械臂 Movelt 学习笔记3 | kinect360相机(v1)相关配置

Why do I have to clean up data?
随机推荐
Can Baidu network disk yundetectservice.exe be disabled and closed
2022 最 NB 的 JVM 基础到调优笔记, 吃透阿里 P6 小 case
Implement a avatar looping control
Upload and download filask files
Video chat source code - one-to-one live broadcast system source code
Coding builds an image, inherits the self built basic image, and reports an error unauthorized: invalid credential Please confirm that you have entered the correct user name and password.
Leetcode 1260. two dimensional grid migration: two solutions (k simulations / one step)
每周小结(*66):下一个五年
Wine wechat initialization 96% stuck
Let me introduce you to the partition automatic management of data warehouse
1. Smoke test
EF core: self referencing organizational structure tree
Install K6 test tool
Two numbers that appear only once in the array
[leetcode weekly replay] 303rd weekly 20220724
2022 Henan Mengxin League game 2: Henan University of technology I - 22
QT | event system qevent
[acwing weekly rematch] 61st weekly 20220723
Grafana - influxdb visual K6 output
Does opengauss support using Sqlalchemy connections?