Lambda表达式可以理解为表示可传递的匿名函数的一种方式,可以简明地传递代码,例如排序:
//java8前的旧方式
public void sortByOld() {
Comparator<Apple> byWeight = new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getWeight().compareTo(o2.getWeight());
}
};
}
//java8新方式
public void sortByLambda() {
Comparator<Apple> byWeight = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
}
//lambda表达式语法
(param)->expression或者(param)->{statements;}
//函数式接口:只有一个抽象方法的接口,这个抽象方法叫函数描述符
//定义函数式接口的语法
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
//Java API内置的函数式接口
Comparable、Runnable、Callable、Predicate、Comsumer、Function
java.util.function.Predicate<T>:接收T类型对象并返回boolean
java.util.function.Comsumer<T>:需要访问类型T的对象,并对其执行某些操作
java.util.function.Function<T>:将输入对象的信息映射到输出中
//Java装箱和拆箱机制,装箱后会需要更多的内存,如何避免自动装箱
//常用的函数式接口
函数式接口 | 函数描述符 | 原始类型特化 |
Predicate<T> | T->boolean | IntPredicate,LongPredicate,DoublePredicate |
Comsumer<T> | T->void | IntComsumer,LongComsumer,DoubleComsumer |
Function<T,R> | T->R | IntFunction<R>,IntToDoubleFunction,IntToLongFunction,LongFunction<R>,LongToDoubleFunction,LongToIntFunction,DoubleFunction<R>,ToIntFunction<T>,ToDoubleFunction<T>,ToLongFunction<T> |
Supplier<T> | ()->T | BooleanSupplier , IntSupplier, LongSupplier, DoubleSupplier |
UnaryOperator<T> | T->T | IntUnaryOperator , LongUnaryOperator, DoubleUnaryOperator |
BiPredicate<L,R> | (L,R)->boolean | |
BiConsumer<T,U> | (T,U)->void | |
BiFunction<T,U,R> | (T,U)->R | |
BinaryOperator<T> | (T,T)->T | IntBinaryOperator ,LongBinaryOperator,DoubleBinaryOperator |
//练习
T->R: Funtion<T,R>
(int,int)->int:IntBinaryOperator.applyAsInt
T->void:Comsumer<T>.accept
()->T:Supplier<T>.get
(T,U)->R:BiFunction<T,U,R>.apply
//Lambda及函数式接口的例子
使用案例 | Lambda的例子 | 对应的函数式接口 |
布尔表达式 | (List<String>list)->list.isEmpty() | Predicate<List<String>> |
创建对象 | ()->new Apple(10) | Supplier<Apple> |
消费一个对象 | (Apple a)->System.out.println(a.getWeight()) | Comsumer<Apple> |
从一个对象中选择或提取 | (String s)->s.length() | Function<String,Integer>或ToIntFunction<String> |
合并两个值 | (int a,int b)->a*b | IntBinaryOperator |
比较两个对象 | (Apple a,Apple b)->a.getWeight().compareTo(b.getWeight()) | Comparator<Apple>或BiFunction<Apple,Apple,Integer> |