一 Lambda表达式
语法:完整的Lambda表达式由三部分组成:参数列表、箭头、声明语句;()-> {};
其中()和{}在只有有一个参数和,一个声明语句时候可以省略
public class Java8Tester public static void main(String args[]) { Java8Tester tester = new Java8Tester(); // 类型声明 MathOperation addition = (int a, int b) -> a + b; // 不用类型声明 MathOperation subtraction = (a, b) -> a - b; // 大括号中的返回语句 MathOperation multiplication = (int a, int b) -> { return a * b; }; // 没有大括号及返回语句 MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); // 不用括号 GreetingService greetService1 = message -> System.out.println("Hello " + message); // 用括号 GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Runoob"); greetService2.sayMessage("Google"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation) { return mathOperation.operation(a, b); } }
执行结果10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Runoob
Hello Google
二 函数式接口
- Supplier函数式接口
- Consumer函数式接口
- Function函数式接口
- Predicate函数式接口
1.自定义函数式接口
1)先定义一个函数式接口
@FunctionalInterface
public interface MessageBuilder {
String buildMessage();
}
2)使用
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 );
}
}
2.Supplier接口
java.util.function.Supplier 接口仅包含一个无参的方法: T get() 。
用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。
3.Consumer接口
java.util.function.Consumer 接口则正好与Supplier接口相反,它不是生产一个数据,而是消费一个数据,
其数据类型由泛型决定。
抽象方法:accept
Consumer 接口中包含抽象方法 void accept(T t) ,意为消费一个指定泛型的数据。基本使用如:
3.Predicate 接口
//数组当中有多条“姓名+性别”的信息如下,请通过 Predicate 接口的拼装将符合要求的字符串筛选到集合 // // ArrayList 中,
需要同时满足两个条件:
// // 必须为女生;
// // 姓名为4个字。
public class DemoPredicate {
public static void main(String[] args) {
String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男", "赵丽颖,女" };
List<String> resultStr=fileter(array,
s ->(s.split(",")[1].equals("女")),
s -> (s.split(",")[0].length()>=4));
resultStr.forEach(s ->{ System.out.println(s); });
}
private static List<String> fileter(String[] array, Predicate<String> one, Predicate<String> two)
{
List<String> temp=new ArrayList<>();
for(String str:array)
{
if(one.and(two).test(str))
{ temp.add(str); } }
return temp; }
}