Lambda表达式
Java
无参
有参
返回值
接口 4种
方法引用
基本概念:
Lambda表达式是特殊的匿名内部类,语法更简洁。
Lambda表达式允许把函数作为一个方法的参数(函数作为方法参数传递),将代码像数据
一样传递。
import java.util.Comparator;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
//匿名内部类
Runnable runnable =new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("子线程执行");
}
};
//Lambda表达式
new Thread(runnable).start();
Runnable runnable2=()->System.out.println("字线程执行2");
new Thread(runnable2).start();
new Thread(()->System.out.println("子线程3")).start();
}
}
案例2
接口
public interface Usb {
void service(int aa);
}
TestUsb
public class TestUsb {
public static void main(String[] args) {
//匿名内部类
Usb mouse=new Usb(){
public void service(){
System.out.println("鼠标开始工作。。。。。。");
}
};
Usb fan=()->System.out.println("风扇开始工作");
run(mouse);
run(fan);
}
public static void run(Usb usb){
usb.service();
}
}
函数式接口
概念:如果一个接口只有一个抽象方法,则该接口称之为函数式接口。
案例演示:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class TestFun {
public static void main(String[] args) {
//Lambda表达式
Consumer<Double> consumer=t->System.out.println("聚餐消费:"+t);
happy(t->System.out.println("聚餐消费:"+t),1000);
happy(t->System.out.println("聚餐消费:"+t),2000);
int[] arr=getNums(()->new Random().nextInt(100),5);
System.out.println(Arrays.toString(arr));
int[] arr2=getNums(()->new Random().nextInt(1000),10);
System.out.println(Arrays.toString(arr2));
String result=handlerString(s->s.toUpperCase(),"hello");
System.out.println(result);
String result2=handlerString(s->s.toUpperCase(),"hello2");
System.out.println(result2);
List<String>list=new ArrayList<>();
list.add("asdfadsffdasasddasff");
list.add("asdfasdfdsfdfasd");
list.add("asdsafasdffd");
list.add("aasdfs");
list.add("as");
List<String> result3 =filterNames(s->s.startsWith("zhang"),list);
System.out.println(result3.toString());
List<String>result4=filterNames(s->s.length()>5,list);
System.out.println(result4);
}
//Consumer消费型接口
public static void happy(Consumer<Double> consumer,double money) {
consumer.accept(money);
}
//Supplier供给型接口
public static int[] getNums(Supplier<Integer>supplier,int count) {
int[] arr =new int[count];
for(int i=0;i<count;i++) {
arr[i]=supplier.get();
}
return arr;
}
//Function函数型接口
public static String handlerString (Function<String,String> function,String str) {
return function.apply(str);
}
//Predicate断言型接口
public static List<String> filterNames(Predicate<String>predicate,List<String> list){
List<String>resultList=new ArrayList<String>();
for (String string : list) {
if(predicate.test(string)) {
resultList.add(string);
}
}
return resultList;
}
}