lambda表达式
接口代码
/**
* 四则运算接口
*/
public interface MathOperation {
public Float operate(Integer a, Integer b);
}
实现代码
public class Test {
public static void main(String[] args) throws Exception {
//1.标准使用方式 实现接口中的方法
//lambda表达式只能用于实现只有一个抽象方法的接口,这样的接口被称为函数式接口
MathOperation add = (Integer a, Integer b) -> {
System.out.println("加法运算");
return (float)(a + b);
};
System.out.println(add.operate(1, 2));
}
}
单个参数可以省略括号。
函数式编程
把代码块作为参数,代码块是一个函数式接口的实现
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Test {
public static void main(String[] args) throws Exception {
//实现Predicate接口
Predicate<Integer> predicate = a -> a>5;
System.out.println(predicate.test(4));
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9);
//再次实现Predicate接口,作为方法参数
filter(list, a -> a%2 == 0);
}
public static void filter(List<Integer> list, Predicate<Integer> predicate) {
for (Integer number : list) {
if (predicate.test(number)) System.out.println(number);
}
}
}
@FunctionalInterface 通知编译器这是一个函数式接口,编译器在编译时会进行检查
实例:实现Function接口生成随机定长字符串
import java.util.Random;
import java.util.function.Function;
public class Test {
public static void main(String[] args) throws Exception {
//实现Function接口,生成随机定长字符串
Function<Integer, String> function = l -> {
String chars = "abcdefghijklmnopqrstuvwxyz1234567890";
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < l; i++) {
int position = random.nextInt(chars.length());
stringBuilder.append(chars.charAt(position));
}
return String.valueOf(stringBuilder);
};
System.out.println(function.apply(4));
}
}