Java8新特性(二)之函数式接口

时间:2023-11-29 21:48:08

.subTitle { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); border-top-left-radius: 7px; border-top-right-radius: 7px; color: rgba(255, 255, 255, 1); height: 1.8em; line-height: 1.8em; padding: 5px }

1. 什么是函数式接口

  1) 只包含一个抽象方法的接口

  2) 使用Lambda表达式去创建该对象。(若Lambda接口抛出一个受检异常,那么该异常需要在接口目标接口的抽象方法上进行声明)

  3) 在任何函数式接口上使用@FunctionalInterface注解,可以检查该接口中是否是一个函数式接口。

2. 常用的JDK自定义的函数式接口(四大核心函数式接口)

    Java8新特性(二)之函数式接口

  1) Consumer<T> 消费型接口

    对类型为T的对象应用操作,包含方法 void accept(T t);

    Java8新特性(二)之函数式接口

  2) Supplier<T> 供给型接口

    返回类型为T的对象,包含方法: T get();

    Java8新特性(二)之函数式接口

  3) Function<T, R> 函数型接口

    对类型为T的对象应用操作,并返回结果为R类型的对象,包含方法为: R apply(T t);

    Java8新特性(二)之函数式接口

  4)Predicate<T> 断定型接口

    确定类型为T 的对象是否满足某约束,并返回类型boolean的值,包含方法为:boolean test(T t);

    Java8新特性(二)之函数式接口

3. 自定义函数式接口

案例一:

/**
* 自定义函数接口
*/
@FunctionalInterface
public interface MyFunctional {
public int getValue();
}

使用测试:

 public static void main(String[] args) {
List<Integer> intList = Arrays.asList(11,22,33,44,55);
for (Integer i : intList) {
MyFunctional myFunctional = () -> i;
System.out.println(myFunctional.getValue());
} }

案例二(含泛型):

/**
* 待泛型的函数式接口
* @param <T>
* @param <R>
*/
@FunctionalInterface
public interface MyTwoArgsInterface<T, R> {
public R retRstr(T t1, T t2);
}

测试案例二:

    @Test
public void test() {
MyTwoArgsInterface<Long, Long> mti = (t1, t2) -> {
return t1 + t2;
};
System.out.println(mti.retRstr(3l,4l));
}