概念
可以把Lambda表达式理解为简洁地表示可传递的匿名函数的一种方式:它没有名称,但它有参数列表、函数主体、返回类型,可能还有一个可以抛出的异常列表。这个定义够大的,让我们慢慢道来。
匿名——我们说匿名,是因为它不像普通的方法那样有一个明确的名称:写得少而想得多!
函数——我们说它是函数,是因为Lambda函数不像方法那样属于某个特定的类。但和方法一样,Lambda有参数列表、函数主体、返回类型,还可能有可以抛出的异常列表。
传递——Lambda表达式可以作为参数传递给方法或存储在变量中。
简洁——无需像匿名类那样写很多模板代码。
有效的Lambda表达式
第一个Lambda表达式具有一个String类型的参 数并返回一个int。Lambda没有return语句,因为已经隐含了return
1. (String s) -> s.length()
第二个Lambda表达式有一个Apple类型的参数并返回一个boolean(苹果的重量是否超过150克)
2.(Apple a) -> a.getWeight() > 150
3.第三个Lambda表达式具有两个int类型的参数而没有返回值(void返回)。注意Lambda表达式可以包含多行语句,这里是两行
3.(int x, int y) -> {
System.out.println("Result:");
System.out.println(x+y);
}
第四个Lambda表达式没有参数,返回一个int
4.() -> 42
第五个Lambda表达式具有两个Apple类型的参数,返回一个int:比较两个Apple的重量
5.(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())
Function<String, Integer> X= new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.parseInt(s);
}
};
Function<String, Integer> XX = (String s) -> Integer.parseInt(s);
Function<String, Integer> XXX = Integer::parseInt;
Function<Integer, Apple> c1 = new Function<Integer, Apple>() {
@Override
public Apple apply(Integer weight) {
return new Apple(weight);
}
};
Apple a1 = c1.apply(100);
Function<Integer, Apple> c2 = Apple::new;
Apple a2 = c2.apply(110);
Function<Integer, Apple> c3 = (weight) -> new Apple(weight);
Apple a3 = c3.apply(110);
ArrayList<Apple> list = new ArrayList<>();
list.sort(new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getWeight().compareTo(o2.getWeight());
}
});
list.sort((Apple o1,Apple o2) -> o1.getWeight().compareTo(o2.getWeight()));
list.sort((o1,o2) -> o1.getWeight().compareTo(o2.getWeight()));
//Comparator<Apple> c = Comparator.comparing((Apple a) -> a.getWeight());
list.sort(Comparator.comparing((a) -> a.getWeight()));
list.sort(Comparator.comparing(Apple::getWeight));
关于复合Lambda 表达式,后面再讲,Lambda 表达式理解起来感觉有点费劲,以后理解了在详细描述.