什么是函数式接口
有且仅有一个抽象方法的接口,比如Android中常用的Runnable
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
常用的lambda表达式和函数式接口是什么关系
一个lambda表达式对应于一个函数式接口,且和函数式接口中那个唯一的抽象方法相匹配
Runnable runnable1 = () -> { System.out.println("runnable 1"); };
Runnable runnable2 = () -> { System.out.println("runnable 2"); };
lambda表达式内使用外部的局部变量需要为final或者确保变量不被修改
String name = "haha";
Runnable runnable3 = () -> { System.out.println("runnable " + name); };
局部变量如果被修改的话不能使用,下面这样则会编译出错:
String name = "haha";
Runnable runnable3 = () -> { System.out.println("runnable " + name); };
name = "new name";
对于类的成员变量和静态变量,lambda表达式内可读可修改
public class FunctionRef {
String language = "java";
static int count = 1;
public void say() {
language = "c++";
count++;
Runnable runnable3 = () -> { System.out.println("runnable " + language); };
}
}
Java内置的函数式接口
Predicate接口
test方法用于条件判断,例如判断字符串的长度是否大于5
boolean test(T t); //Predicate接口中的test方法
Predicate<String> predicate = (fruit) -> fruit.length() > 5;
predicate.test("apple"); //false
predicate.test("watermelon"); //true
Function接口
apply方法用于类型转换
public interface Function<T, R> {
R apply(T t); //T类型转为R类型
}
例如将String类型转为Integer类型
Function<String,Integer> stringToInteger = Integer::valueOf;
stringToInteger.apply("123"); //123
Consumer接口
accept方法接收一个参数并执行
public interface Consumer<T> {
void accept(T t);
}
例如打招呼
Consumer<String> consumer = (name) -> { System.out.println("good morning, " + name); };
consumer.accept("lisa");