目录
第一篇:JDK8新特性一:引入介绍
第二篇:JDK8新特性二:Lambda表达式引入介绍
第三篇:JDK8新特性二:Lambda表达式规范和语法
第四篇:JDK8新特性二:方法引入详述
第五篇:JDK8新特性二:foreach、排序、线程调用简单示例
第六篇:JDK8新特性三:Stream流+常见方法演示
第七篇:JDK8新特性四:Optional类的学习
JDK8新特性
3 Lambda表达式规范
-
使用Lambda表达式需要依赖函数接口
-
函数接口定义
- 在接口中只能有一个抽象方法
- @FunctionalInterface标记该接口为函数接口
- 可以通过default修饰为普通方法或者通过static修饰为静态方法
- 可以定义Object类中的public方法
-
代码演示函数接口及说明
-
函数接口
package com.fc.service; /** * @ClassName FunctionService * @Description 函数接口,使用注解声明 * @Author Fclever * @Date 2021/7/19 21:28 */ // 使用@FunctionalInterface注解标识函数接口 @FunctionalInterface public interface FunctionService { // 1. 定义一个抽象方法 void add(int x, int y); // 2. 再定义一个抽象方法,@FunctionalInterface会报错 // 错误信息为:在该接口中出现了不止一个未被实现的方法 // void get(); // 3. 可以定义default方法,需要含有方法体 default void get() { System.out.println("get()"); } // 4. 可以定义static方法,需要含有方法体 static void put() { System.out.println("put()"); } // 5. 可以定义Object类中的方法 /** * Object父类中的public方法可以在函数接口中重写 * 不能包含Object类中的final修饰的方法 * * @return */ int hashCode(); boolean equals(Object o); String toString(); /** * Object类中的clone方法也不可以存在 * protected修饰 */ // Object clone(); // void finalize(); /** * Object类中的final修饰的方法不允许存在 */ // void notify(); // void notifyAll(); // void wait(long l); // void wait(long l,int t); // void wait(); }
-
-
JDK中常见的函数接口
java.lang.Runnable java.util.concurrent.Callable java.security.PrivilegedAction java.util.Comparator java.io.FileFilter java.nio.file.PathMatcher java.lang.reflect.InvocationHandler java.beans.PropertyChangeListener java.awt.event.ActionListener javax.swing.event.ChangeListener
- Runnable接口示例
- Runnable接口示例
4 Lambda基础语法
-
语法介绍
(a,b)->{ System.out.println("Lambda"); }
- ():表示函数方法的参数列表,a和b就是两个参数
- ->:表示分隔
- {}:表示方法体
-
示例
-
无参方法调用
@FunctionalInterface public interface TestInterface { void test(); } // 示例 TestInterface obj = () -> { System.out.println("Lambda"); }; // 调用 ((TestInterface)() -> { System.out.println("Lambda"); }).test();
-
带参方法调用
@FunctionalInterface public interface TestInterface { void test(int a,int b); } // 示例,这里的a,b表示形参,并非实际传递给test方法的形参值 TestInterface testInterface = (a, b) -> { System.out.println("Lambda"); }; // 调用 ((TestInterface)(a,b) -> { System.out.println("Lambda"); }).test(1,2);
-
含有返回值
TestInterface obj = (a,b) -> { System.out.println("Lambda"); return a + b; }; // 调用,结果是方法返回值 ((TestInterface)(a,b) -> { System.out.println("Lambda"); return a + b; }).test(1,2);
-
-
精简语法说明
-
当方法体内只有一条语句的时候,不需要写{}
() -> System.out.println("Lambda");
-
当方法体内只有一条语句并且该语句时return时,不需要写return,直接写返回结果即可
public interface TestInterface{ int add(int i,int j); } int result = ((TestInterface)(i,j) -> i + j).add(1,2);
-