Java lambda表达式
Java 8 引入Lambda表达式,使代码更加简洁(Java8 = JDK8 = JDK1.8)
Lambda表达式本质上是个匿名方法,用于实现函数式接口定义的唯一抽象方法
函数式接口
1、有且仅有一个抽象方法
2、允许接口中存在静态方法、默认方法或其他非抽象方法
3、可用 @FunctionalInterface 注解标识函数式接口,如果不符合定义则会报错(非强制)
例1:
1 @FunctionalInterface 2 interface IFS1 { 3 void IFun(); 4 }
例2:
虽然 IFS2 没有定义抽象方法,但是继承了 IFS1 的抽象方法,其他方法为非抽象方法
1 @FunctionalInterface 2 interface IFS2 extends IFS1 { 3 // 默认方法 4 default void fun1() { 5 System.out.println("default"); 6 } 7 // 静态方法 8 static void fun2 () { 9 System.out.println("static"); 10 } 11 // Object定义的公有方法 12 boolean equals(Object obj); 13 }
Lambda 表达式
Lambda表达式的一般形式
(参数) -> { 方法体 };
参数唯一时可省略 ()
方法体只有一句时可省略 {}
参数类型可一起省略
Lambda表达式使用举例
1 // 准备一个接口 2 @FunctionalInterface 3 interface IFS1 { 4 void IFun(); 5 } 6 7 // lambda 实现接口 8 IFS lambda = () -> System.out.println("lambda"); 9 // 调用 10 lambda.IFun();
遍历容器
1 Map<Integer, String> map = new HashMap<>(); 2 3 // 常规遍历 HashMap 4 for (Map.Entry<Integer, String> e : map.entrySet()) { 5 System.out.println(e.getKey() + " : " + e.getValue()); 6 } 7 // lambda表达式遍历 HashMap 8 map.forEach((k, v) -> System.out.println(k + " : " + v));
实现 Runnable 接口
1 public void myThread() { 2 new Thread(new Runnable() { 3 @Override 4 public void run() { 5 System.out.println("匿名内部类实现线程"); 6 } 7 }).start(); 8 new Thread(() -> System.out.println("lambda实现线程")).start(); 9 }
实现 Comparator 接口
1 List<Point> list = new ArrayList<>(); 2 3 // 匿名内部类排序 4 list.sort(new Comparator<Point>() { 5 @Override 6 public int compare(Point o1, Point o2) { 7 return o1.x == o2.x ? o1.x - o2.x : o1.y - o2.y; 8 } 9 }); 10 11 // lambda排序 12 Collections.sort(list, (p1, p2) -> p1.x == p2.x ? p1.x - p2.x : p1.y - p2.y);
方法引用
Stream API