关于java8的特性:lambda表达式
lambda表达式可以理解为一种匿名函数:没有名称、有参数列表、函数主体、返回类型,可能还会有异常的列表。
lambda表达式:(参数) -> 表达式 或者是 (参数) -> { java语句; }
函数式接口
什么是函数式接口
函数式接口就是仅仅定义了一个抽象方法的接口,类似于predicate、comparator和runnable接口。
@FunctionalInterface
@FunctionalInterface 函数式接口都带有这个注解,这个注解表示这个接口会被设计为函数式接口。
什么是行为参数化
一个方法接受多个不同的行为作为参数,并在内部使用它们,完成不同行为的能力。
必须知道的四大核心函数式接口
Consumer接口源码(有参,无返回值)
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
使用方法:
public static void test1() {
Consumer<Float> consumer = (x) -> {System.out.println("He consumes " + x + "¥");};
consumer.accept((float) 50.5);
}
Supplier接口源码(无参,有返回值)
@FunctionalInterface
public interface Supplier<T> {
T get();
}
使用方法:
public static void test2(){
Supplier<Integer> supplier =
() -> {
String s = "hello world";
Integer n = s.length();
return n;
};
Integer n = supplier.get();
System.out.println("n 的值为:" + n);
}
Function接口源码(有参,有返回值)
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
使用方法:
public static void test3(){
Function<List<Integer>, Integer> function =
(x) -> {
int n = x.size();
Integer value = x.get(n-1);
return value;
};
List<Integer> list = Arrays.asList(1, 2, 3);
Integer lastValue = function.apply(list);
System.out.println("The lastValue is " + lastValue);
}
Predicate接口源码(有参,返回值为boolean)
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
使用方法:
public static void test4(){
Predicate<String> predicate =
(x) -> {
int n = x.length();
if (n > 10) {
System.out.println("n 大于 10");
return true;
}else {
System.out.println("n 小于 10");
return false;
}
};
predicate.test("Hello world!");