package com.example.demo.lambda;
import java.util.ArrayList;
import java.util.List;
public class test {
public static void main(String[] args) {
//介绍:目的是在使用但接口(只含有一个方法的几口)匿名类时,让代码更加简洁
//lambada表达式通常就是一个匿名方法(函数)
//1.原始
StudentService studentService= new StudentService() {
@Override
public String work() {
return "222";
}
};
System.out.println(studentService.work());
//2.简化后,就是将类名方法名都去掉,然后加上一个->符号
StudentService studentService2 = ()-> "2333";
System.out.println(studentService2.work());
//==========================================================
//1.原始
TargetThread targetThread = new TargetThread();
Thread thread = new Thread(targetThread);
thread.start();
//2.第一步简化
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("ok1");
}
});
thread1.start();
//3.再一步简化
Thread thread2 = new Thread(() -> {
System.out.println("ok2");
}
);
thread2.start();
//=================================
List<Integer> s = new ArrayList<>();
s.add(11);
s.add(13);
s.add(9);
s.sort((Integer o1, Integer o2) ->{
return o1 - o2;
});
System.out.println(s);
}
}
interface StudentService {
String work();
}
class TargetThread implements Runnable{
@Override
public void run() {
System.out.println("ok");
}
}
lambda表达式简单使用
最新推荐文章于 2022-06-23 13:56:31 发布