项目中用到的 JDK 7、JDK 8 的新特性(2)Lambda 表达式
2、Lambda表达式
从 JDK 8 开始,Java 中引入了一个 FunctionalInterface 的概念。FunctionalInterface 即只定义了一个方法的接口,例如:
public interface Runnable {
void run();
}
public interface Callable {
V call();
}
public interface Consumer {
void accept(T t);
}
public interface BiConsumer {
void accept(T t, U u);
}
等等。而 Lambda 表达式可以让我们用更少的代码来实现 FunctionalInterface 的匿名类。
例如:
Thread thread = new Thread(new Runnable() {
@Override public void run() {
doSomething();
}
}
可以用 Lambda 表达式写为:
Thread thread = new Thread(() -> {
doSomething();
});
如果代码块里只有一行代码,还可以省略掉大括号:
Thread thread = new Thread(() -> doSomething());
又例如:
Function> function = new Function<>() { @Override public List accept(String str) { list.add(str); return list; } };
可以用 Lambda 表达式写为:
Function> function = (str) -> { list.add(str); return list; };
再例如:
Supplier> supplier = new Supplier<>() { @Override public Set get() { return new HashSet (); } };
可以用 Lambda 表达式写为:
Supplier> supplier = () -> { return new HashSet (); };
由于代码块里只有一行代码,可以省略掉大括号和 return 关键字:
Supplier> supplier = () -> new HashSet ();
如果 lambda 表达式对应的 FunctionalInterface 的方法没有参数,而且方法体内直接调用一个类的无参构造方法来返回一个对象的话,还可以使用 Class::new 这样的语法进一步简化代码:
Supplier> supplier = HashSet::new;