文档
定义函数式接口
package com.github.mouday.demo; /** * 定义一个函数式接口 */ @FunctionalInterface public interface GreetingService { void sayMessage(String message); }
实现接口
package com.github.mouday.demo; public class Demo { public static void main(String[] args) { // 使用Lambda表达式来表示该接口的一个实现 GreetingService greetingService = message -> System.out.println("hello: " + message); greetingService.sayMessage("Tom"); // hello: Tom } }
Java8提供的 Predicate接口定义
@FunctionalInterface public interface Predicate<T> { boolean test(T t); }
Predicate接口使用
package com.github.mouday.demo; import java.util.*; import java.util.function.Predicate; public class Demo { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); // 输出所有值 eval(list, o -> true); // 1 2 3 4 5 6 // 输出所有偶数值 eval(list, o -> o % 2 == 0); // 2 4 6 // 输出所有大于3的数值 eval(list, o -> o > 3); // 4 5 6 } public static void eval(List<Integer> list, Predicate<Integer> predicate) { for (Integer i : list) { if (predicate.test(i)) { System.out.printf("%d ", i); } } System.out.println(); } }