目录
lambda表达式
函数式接口
方法引用
默认方法
lambda表达式
- 允许将一个函数作为一个方法的参数 ()->{}
函数式接口
只有一个抽象方法 多个非抽象方法的接口
标志 @FunctionInterface
例如:
@FunctionInterface
public interface Runnable {
public abstract void run();
}
四大函数式接口
只有一个抽象方法 多个非抽象方法的接口
标志 @FunctionInterface
Function、Predicate、Supplier、Consumer
Function 函数型接口:有一个输入参数类型,有一个输出类型
// 1 Function Functionfunction = new Function () { @Override public String apply(String t) { return "hello~"+t; } }; // 2 只要是 函数型接口 可以 用 lambda表达式简化 Function function = (str)->{return "hello"+str;}; System.out.println(function.apply("zhangsan"));
Predicate 断定型接口:有一个输入参数,返回值只能是 布尔值!
public static void TestPredicate() {
Predicate pre = (s)->{return s.isEmpty(); };
System.out.println("字符串为空吗?"+pre.test("aaa"));
}
Consumer 消费型接口: 只有输入,没有返回值
public static void TestConsumer() {
Consumer c = (food)->{System.out.println("吃了:"+food);};
c.accept("苹果");
}
Supplier 供给型接口: 没有参数,只有返回值
public static void TestSupplier() {
Supplier s = ()->{return "banana";};
System.out.println("提供了:"+s.get());
}
方法引用
直接引用已有的java类或实例的方法,一般和lambda表达式一起使用
使代码更简洁、减少代码冗余
使用 ::
例如:System.out::println
public class Test{
public static void main(String[] args)
{
//lambda表达式使用:
Arrays.asList(new String[] {"a", "c", "b"}).stream().forEach(s -> Test.println(s));
//静态方法引用:
Arrays.asList(new String[] {"a", "c", "b"}).stream().forEach(Test::println);
}
public static void println(String s)
{
System.out.println(s);
}
}
默认方法
补充:从匿名内部类到lambda表达式(再方法应用)的演变
// 以Consumer函数式接口为例 ,有一个参数,无返回值
Arrays.asList(new String[] {"a", "c", "b"}).stream().forEach(new Consumer() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
// 转为lambda表达式
Arrays.asList(new String[] {"a", "c", "b"}).stream().forEach(
(x)->{System.out.println(x);}
);
// 一个参数,()可以省略,一条语句,{} 和 ; 一起省略
Arrays.asList(new String[] {"a", "c", "b"}).stream().forEach(
x->System.out.println(x)
);



