Java-jdk1.8新特性之Lambda表达式(一)
Lambda表达式是一个匿名函数,可以吧Lambda表达式理解为一段可以传递的代码(将代码像参数一样进行传递),可以写出更简洁灵活的代码,使Java语言表达能力得到提升。
lambda表达式的形式和定义 ( 形参列表 ) -> { 函数主体 return 返回类型 }
举个栗子 现在,我们拥有一堆苹果,并希望将苹果按照不同的条件筛选出来,在Java1.8之前,我们通过定义一个过滤器接口来实现:
//定义一个苹果类 public class Apple{ private Long id; private String color; private Double weight; private String orgin; public Apple(){ } public Apple(Long id,String color,Double weight,String orgin){ this.color = color; this.weight = weight; this.id = id; this.orgin = orgin; } //省略getter和setter方法 }
public interface AppleFilter{ boolean accept(Apple apple); } public static List<Apple> filterApple(List<Apple> apples,AppleFilter filter){ List<Apple> filterApples = new ArrayList<>(); for(Apple apple:apples){ //把符合条件的苹果添加到集合中去 if(filter.accept(apple)){ filterApples.add(apple); } } return filterApples; }
将行为抽象化之后,可以在具体调用的地方设置筛选条件,并将条件作为参数传递到方法中去
public static void main(String[] args) { // 要过滤的苹果集合 List<Apple> apples = new ArrayList<>(); List<Apple> filterApples = filterApple(apples, new AppleFilter() { @Override public boolean accept(Apple apple) { if ("red".equals(apple.getColor()) && apple.getWeight()>=10) { return true; } return false; } }); System.out.println(filterApples); }
当我们采用Lamba表达式时,代码就会变得十分精简,使用Lamba表达的代码书写如下:
public static void main(String[] args){ //要过滤的苹果集合 List<Apple> apples = new ArrayList<>(); List<Apple> apples = filterApple(apples,(Apple apple)->{ return "red".equals(apple.getColor())&&apple.getWeight()>=10; }); System.out.println(apples); }
Lambda表达式和return关键字 lambda表达式隐含了return关键字,在单个的表达式中,我们无需显式的写return关键字,但当表达式是一个语句的集合时候需要添加return关键字,并用花括号把多个lamba表达式包围起来。 1、无参数,隐藏return
public interface StringLength { int getLength(); } public static void main(String[] args) { StringLength sl = () -> 5; System.out.println(sl.getLength()); }
2、有参数,隐藏return
public interface StringLength { int getLength(String str); } public static void main(String[] args) { StringLength sl = (String str) -> str.length(); System.out.println(sl.getLength("abc")); }
3、有多个参数,显式return
public interface StringLength { int getLength(String str1,String str2); } public static void main(String[] args) { StringLength sl = (str1,str2) -> { // Lambda 体 int len1 = str1.length(); int len2 = str2.length(); return len1 + len2; }; System.out.println(sl.getLength("abc","123")); }
【注意】Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文可以自行推断。 函数式接口 函数式接口就是只定义一个抽象方法的接口,函数式接口最常使用方式,就是将函数式接口作为一个方法的参数进行传递。 【注意】函数式接口(Functional interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口,比如静态方法等。
上一篇:
IDEA上Java项目控制台中文乱码