lambda常见语法格式
- 无参,无返回值
() -> System.out.println
- 有返回值
() -> "abc";
- 方法引用
ContainingClass::staticMethodName
函数式接口
函数式接口只包含一个抽象方法声明接口。使用@FunctionalInterface
注解。这样函数式接口只能有一个抽象方法,如果你尝试添加第二个抽象方法
public class StudentTest {
@Test
public void testA() {
CustomFn<String> customFn = (val) -> val == "a";
System.out.println(customFn.test("a"));
}
}
使用函数式接口
CustomFn<String> customFn = (val) -> val == "a";
System.out.println(customFn.test("a"));
其他
java JDK中提供java.util.function
提供了方便的使用方法
image.png
stream Filter方法
看源码定义 Stream<T> filter(Predicate<? super T> predicate);
。传递是一个Predicate
返回bool类型