- /*
- * 自定义函数式接口:
- * 1, 声明一个接口, 只能包含一个抽象方法
- * 2, 给这个接口加 @FunctionalInterface
- */
- public class Test {
- public static void main(String[] args) {
- //IntCalc tools 形参, 函数式接口, 可以 Lambda 表达式赋值
- /*
- * (1) 抽象方法: int cal(int a , int b);
- * (2) 如何实现抽象方法
- * 例如: 求 a+b 的和
- */
- getProduct(1,2, (int a , int b) -> {return a+b;});//new 了一个 IntCalc 的实现类的对象, 而且实现了 IntCalc 抽象方法
- getProduct(1,2, (a ,b) ->a*b);
- }
- //2, 在测试类中定义 public static void getProduct(int a , int b ,IntCalc tools),
- // 该方法的预期行为打印使用 tools 的 cal(a,b) 的计算结果
- public static void getProduct(int a , int b ,IntCalc tools){
- int result = tools.cal(a, b);
- System.out.println("结果:" + result);
- }
- }
- //1, 定义一个函数式接口 IntCalc, 其中抽象方法 int cal(int a , int b), 使用注解 @FunctionalInterface
- @FunctionalInterface
- interface IntCalc{
- int cal(int a , int b);
- }
- public class Test05 {
- public static void main(String[] args) {
- test01();
- }
- public static void test01() {
- List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
- /*
- * default void forEach(Consumer<? super T> action)
- * 形参的类型是 Consumer 接口, 可以使用 Lambda 表达式赋值
- * Consumer<T> void accept(T t)
- *
- */
- list.forEach(num -> System.out.println(num));
- }
- /*
- 源代码
- default void forEach(Consumer<? super T> action) {
- Objects.requireNonNull(action);
- for (T t : this) {
- action.accept(t);
- }
- }
- */
- }
来源: http://www.bubuko.com/infodetail-3460718.html