Lambda 表达式
语法
(参数) -> {方法体}
A res1 = () -> System.out.println("test方法");
A res2 = (a, b) -> System.out.println(a);
A res3 = (a, b) -> a + b;
A res4 = (a, b) -> { return a + b; };
interface A {
void test();
void add(int a, int b);
int add(int a, int b);
}
函数式接口
定义:只包含一个抽象方法的接口 称为函数式接口
Lambda表达式和函数式接口的关系:
Lambda表达式就是一个函数式接口的实例
内置函数式接口
Predicate<T>断定型接口
断定型接口,接受一个输入参数,返回一个布尔值结果。
class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
System.out.println(list);
//输出所有偶数:
eval(list, integer -> integer % 2 == 0);
//输出大于 3 的所有数字
eval(list, i -> i > 3);
}
public static void eval(List<Integer> list, Predicate<Integer> predicate) {
for (Integer n : list) {
if (predicate.test(n)) {
System.err.print(n + "\t");
}
}
}
}
Supplier 供给型接口
本质就是一个容器,可以用来存储数据(或者是产生数据的规则),然后可以供其他方法使用的这么一个接口。
class Main {
public static void main(String[] args) {
Supplier<Integer> supplier = new Supplier<Integer>() {
@Override
public Integer get() {
return new Random().nextInt(100);
}
};
System.out.println(supplier.get());
System.out.println(supplier.get());
//这里Supplier.get()等价于new Random().nextInt(100)
}
}
Consumer<T>消费型接口
与Supplier接口相反,它不是生产一个数据,而是消费一个数据其数据类型由泛型决定
class Main {
public static void main(String[] args) {
eval("codingfuture", new Consumer<>() {
@Override
public void accept(String s) {
System.out.println(s.toUpperCase());
}
});
}
public static void eval(String name, Consumer<String> consumer) {
consumer.accept(name);
}
}
Function<T,R>函数型接口
对类型为T的对象应用操作返回类型为R的对象
class Main {
public static void main(String[] args) {
//字符串 转换 Integer
Integer trimStr = strHandler("666", s -> Integer.valueOf(s));
System.out.println(trimStr);
}
//对类型为T的对象应用操作返回类型为R的对象 Function<T,R>
public static Integer strHandler(String str, Function<String, Integer> fun) {
return fun.apply(str);
}
}
自定义函数接口
@FunctionalInterface
public interface Operation {
int add(Integer num1, Integer num2);
}
class Main {
public static void main(String[] args) {
eval(12, 13, (num1, num2) -> num1 + num2);
}
public static void eval(int a, int b, Operation operation) {
int res = operation.add(a, b);
System.out.println(res);
}