好程序员分享java8新特性之Lambda表达式
什么是Lambda?
interface Comparator<T> {
int compare(T o1, T o2);
}
class Program {
public static void main(String[] args) {
class Impl implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
Comparator<Integer> c1 = new Impl();
Comparator<Integer> c2 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
Comparator<Integer> c3 = (o1, o2) -> o1 - o2;
}
}
@FunctionalInterface**
@FunctionalInterface
参数: 以()包围起来,多个参数以逗号分隔
(int a, int b)
{ System.out.println("hello world"); }
(int a, int b) -> {};
() -> { System.out.println("hello world"); };
(int a, int b) -> { System.out.println(a + b); };
// int, int参数、int返回值
(int a, int b) -> { return a + b; };
三、Lambda表达式语法精简
实现的时候,对应的部分可以省略参数精简
- 参数的类型可以精简
(int a, int b) -> { System.out.println(a + b); }
可以精简为:
(a, b) -> { System.out.println(a + b); }
(int a) -> { System.out.println(a); }
可以精简为:
a -> { System.out.println(a); }
a -> { System.out.println(a); }
可以精简为:
a -> System.out.println(a);
a -> { return a * 2; }
可以精简为:
a -> a * 2;
interface Calculate {
int calculate(int a, int b);
}
public class Program {
public static void main(String[] args) {
Calculate c = (a, b) -> a + b;
}
public static int add(int a, int b) {
return a + b;
}
造:
Calculate c = Program::add;
interface CreatePerson {
Person getPerson();
}
class Person {}
class Program {
public static void main(String[] args) {
CreatePerson c = Person::new;
}
}
五、Lambda表达式之综合案例: 排序Comparator
// 排序
list.sort((o1, o2) -> o2.age - o1.age);
TreeSet<Person> set = new TreeSet<>((o1, o2) -> {
if (o1.age >= o2.age) {
return -1;
}
else {
return 1;
}
});
list.forEach(System.out::println);
// 输出集合中所有的偶数
list.forEach(ele -> {
if (ele % 2 == 0) {
System.out.println(ele);
}
});
七、Lambda表达式之综合案例: removeIf()
list.removeIf(ele -> ele.age > 10);
new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}).start();
参
数
Predicate T boolean
IntPredicate :参数:int,返回值:boolean
LongPredicate :参数:long,返回值:boolean
DoublePredicate :参数:double,返回值:boolean
Consumer T void
IntConsumer :参数:int,返回值:void LongConsumer :
参数:int,返回值:void DoubleConsumer :参数:int,返
回值:void
Function<T, R> T R
IntFunction<R> :参数:int,返回值:R
IntToDoubleFunction :参数:int,返回值:double
IntToLongFunction :参数:int,返回值:long
LongFunction<R> :参数:long,返回值:R
LongToDoubleFunction :参数:long,返回值:double
LongToIntFunction :参数:long,返回值:int
DoubleFunction<R> :参数:double,返回值:R
DoubleToIntFunction :参数:double,返回值:int
DoubleToLongFunction :参数:double,返回值:long
double
UnaryOperator T T
IntUnaryOperator :参数:int,返回值:int
LongUnaryOperator :参数:long,返回值:long
DoubleUnaryOperator :参数:double,返回值:double
BinaryOperator T,
T T
IntBinaryOperator :参数:int, int,返回值:int
LongBinaryOperator :参数:long, long,返回值:long
DoubleBinaryOperator :参数:double, double,返回值:
double
BiPredicate<L,
R>
L,
R boolean
BiConsumer<T,
U>
T,
U void
BiFunction<T,
U, R>
T,
U R
来源:51CTO
作者:wx5d42865f47214
链接:https://blog.51cto.com/14479068/2433704