1.1概念:java中有且只有一个抽象方法的接口。
1.2格式:
修饰符 interface 接口名称 { public abstract 返回值类型 方法名称(可选参数信息); // 其他非抽象方法内容 } //或者 public interface MyFunctionalInterface { void myMethod(); }
@FunctionalInterface public interface MyFunctionalInterface { void myMethod(); }
public class Demo09FunctionalInterface { // 使用自定义的函数式接口作为方法参数 private static void doSomething(MyFunctionalInterface inter) { inter.myMethod();
// 调用自定义的函数式接口方法 } public static void main(String[] args) { // 调用使用函数式接口的方法 doSomething(() ‐> System.out.println("Lambda执行啦!")); } }
public class Demo01Logger { private static void log(int level, String msg) { if (level == 1) { System.out.println(msg); } } public static void main(String[] args) { String msgA = "Hello"; String msgB = "World"; String msgC = "Java"; log(1, msgA + msgB + msgC); } }
@FunctionalInterface public interface MessageBuilder { String buildMessage(); }
public class Demo02LoggerLambda { private static void log(int level, MessageBuilder builder) { if (level == 1) { System.out.println(builder.buildMessage()); } } public static void main(String[] args) { String msgA = "Hello"; String msgB = "World"; String msgC = "Java"; log(1, () ‐ > msgA + msgB + msgC ); } }
public class Demo03LoggerDelay { private static void log(int level, MessageBuilder builder) { if (level == 1) { System.out.println(builder.buildMessage()); } } public static void main(String[] args) { String msgA = "Hello"; String msgB = "World"; String msgC = "Java"; log(2, () ‐ > {System.out.println("Lambda执行!"); return msgA + msgB + msgC; }); } }
public class Demo04Runnable { private static void startThread(Runnable task) { new Thread(task).start(); } public static void main(String[] args) { startThread(() ‐ > System.out.println("线程任务执行!")); } }
import java.util.Arrays; import java.util.Comparator; public class Demo06Comparator { private static Comparator<String> newComparator() { return (a,b) ‐>b.length() ‐a.length(); } public static void main(String[] args) { String[] array = {"abc", "ab", "abcd"}; System.out.println(Arrays.toString(array)); Arrays.sort(array, newComparator()); System.out.println(Arrays.toString(array)); } }
原文:https://www.cnblogs.com/qqfff/p/13204395.html