Java8_Lambda表达式初识

Lambda表达式到底是什么

让我们从一个最常用的例子说起,Java8之前我们循环一个List的时候一般会这样写:

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
        
for(Integer integer : list){
    System.out.println(integer);
}

在Java8中我们可以这样写:

第一种:
list.forEach(new Consumer<Integer>() {
    @Override
    public void accept(Integer integer) {
        System.out.println(integer);
    }
});

是不是看起来好像更繁琐了呢,别着急,我们继续变化一下:

第二种:
list.forEach(integer -> {System.out.println(integer);});

这里就是使用了Lambda表达式,
我们进入forEach方法的源码来看一下:

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

方法的参数是一个Consumer,我们来看看这个Consumer

/**
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
}

Consumer是Java8开始提供的一个接口,我们看到这个接口有一个注解@FunctionalInterface,使用这个注解的接口被称为“函数式接口”,我们来看下什么叫函数式接口:

函数式接口 FunctionalInterface
1.如果一个接口只有一个抽象方法,那么该接口就是一个函数式接口
2.如果我们在某个接口上声明了FunctionalInterface注解,那么编译器就会按照函数式是接口的要求该接口
3.如果某个接口只有一个抽象方法,但我们并没有给该接口声明FunctionalInterface注解,那么编译器依旧会将该接口看作是函数式接口

4.Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
 一个函数式接口的实例对象可以使用lambda表达式、方法引用、构造方法来创建

这里提到了lambda表达式,这里就解释了为什么本文一开始第一种写法到第二种写法的转变。使用integer -> {System.out.println(integer);}lambda表达式来创建Consumer这个函数式接口。

接触过js之类语言的同学肯定很眼熟,在js中函数参数是一个函数,返回值是另一个函数是很常见的,但是在之前的Java中我们无法将函数作为一个参数传递给一个方法,也无法声明返回一个函数的方法。

为此Java8引入了Lambda表达式来提供这种方法,integer -> {System.out.println(integer);}在这里作为参数,传递给 forEach 方法,我们可以把这理解为是一种“行为”,我们是把一种“行为”传递给这个方法,这样做提升了抽象层次,使得API重用性更好,更加灵活。

Lambda表达式的结构

一个Lambda表达式主要有以下部分组成:参数列表,箭头(->),以及一个表达式或语句块。
 (arg1,arg2) -> {body}
  1. 一个Lambda表达式可以有零个或多个参数,参数在圆括号里,参数之间逗号分隔;

  2. 空圆括号代表参数集为空;

  3. 当只有一个参数,且其类型可推导时,圆括号()可省略

    (x,y) -> {return x + y}
    () -> {return x + y}
    x -> x*x
    
  4. 参数的类型既可以明确声明,也可以根据上下文来推断

    不声明:(x,y) -> {return x+y;}
    声明:(int x,int y) -> {return x+y;}
    
    
  5. 如果Lambda表达式的主体只有一条语句,花括号{}可以省略。匿名函数的返回类型与该主体表达式一致

  6. 如果是一条语句以上,表达式必须放在华括号{}里(形成代码块)

    省略前:(int x,int y) -> {return x + y;}
    省略后:(int x,int y) -> x + y
    

常用的Lambda表达式

  1. Consumer :

/**
* Consumer
* 接收一个参数不返回
* void accept(T t);
*/
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
list.forEach(integer -> { System.out.println(integer); });
  1. Function:
/**
* Function
* 接收一个参数,返回一个值
* R apply(T t);
*/
int result = test.calc(5, value -> value * value); //25
int result2 = test.calc(5, value -> value - 2); //3

    
public int calc(int a,Function<Integer,Integer> function){
    return function.apply(a);
}

3.BiFunction

/**
 * BiFunction
 * 接收两个参数,返回一个值
 * R apply(T t, U u);
 */
int result1 = test.calc(3, 4, (a, b) -> a + b);//7
int result2 = test.calc(3, 4, (a, b) -> a * b);//12


public int calc(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
    return biFunction.apply(a, b);
}
  
  1. Comparator
  /**
 * Comparator
 * 接收两个参数,返回int
 * int compare(T o1, T o2);
 */
List<Integer> list = Arrays.asList(6,2, 8, 5, 9, 1, 4, 3);
Collections.sort(list,(a,b) -> a.compareTo(b));
list.forEach(item-> System.out.print(item));//12345689

5.Predicate

/**
 * Predicate
 * 接收一个参数,返回布尔值
 * boolean test(T t);
 */
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
Predicate<Integer> p1 = value -> value % 2 == 0;
Predicate<Integer> p2 = value -> value > 5;
list.stream().filter(p1).collect(Collectors.toList()).forEach(item -> System.out.print(item));//2468
list.stream().filter(p1.and(p2)).collect(Collectors.toList()).forEach(item -> System.out.print(item));//68

6.Supplier

/**
 * Supplier
 * 不接收参数返回一个值
 * T get();
 */
Supplier<Student> supplier = () -> new Student();
Student student = supplier.get();
    原文作者:大鹏_xzlp
    原文地址: https://www.jianshu.com/p/b45ebd1d3d88
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞