jdk8新特性之Lamda表达式

Lamda表达式的形式与意义

Lamda表达式的形式为左侧为参数列表,右侧为函数体或Lamda体。
Lamda表达式的出现是Java对函数式编程的兼容,可以通过与函数式接口的组合进行数据处理;不使用Lamda表达式时,对数据处理需要写一个固定方法,当需要多种类别的数据处理时,由于具体处理形式不同,导致无法进行方法抽取,冗余较大;而使用Lamda表达式的时候,通过函数式接口作为方法的参数列表,将除去数据处理的代码封装在该方法中,而在目标位置使用Lamda表达式进行调用即可。

Lamda表达式的格式

Lamda表达式可以有多种格式,分别为:无参无返回值、有一个参数无返回值、有多个参数有返回值并且Lamda体中有多条语句。
Lamada需要搭配函数式接口进行使用;函数式接口即只有一个抽象方法的接口,可以使用@FunctionalInterface。
Lamada表达式就是语法糖,底层还是方法的执行。

无参数无返回值格式

	@Test
    public void noParam() {
    
    
        Runnable r1 = () -> System.out.println("Hello");
        r1.run();
    }

一个参数无返回值格式

	// 本例子中的Lamda表达式的左侧括号可以不写
	@Test
    public void oneParam() {
    
    
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("admin");
    }

有多个参数有返回值并且Lamda体中有多条语句

多个参数有返回值,其中左侧的参数列表中可以写参数类型,也可以不写,JVM会根据上下文进行类型推断。若Lamda体中只有一条语句,return和’{}'都可以省略为:

(x, y) -> x-y;

	@Test
    public void moreParamReturn() {
    
    
        Comparator<Integer> com = (x, y) -> {
    
    
            System.out.println("jin");
            return x-y;  
        };
    }

Lamda的使用

Lamda需要搭配函数式接口使用。如下两种使用方法。
但Lamda的出现主要是为了开始支持函数式编程,所以一般采用调用方法的形式来进行使用,即在方法参数中包含接口的使用方法,在方法内部使用调用后在主方法中进行Lamda表达式的实现。

	@FunctionalInterface
	public interface Func {
    
    
	    public Integer get(Integer a, Integer b);
	}

	@Test
    public void sum() {
    
    
        Func add = (x, y) -> x+y;
        Integer integer = add.get(5, 6);
        System.out.println(integer);

        Integer opration = opration(5, 8, ((a, b) -> b - a));
        System.out.println(opration);
    }

    public Integer opration(Integer a, Integer b, Func func) {
    
    
        return func.get(a, b);
    }

猜你喜欢

转载自blog.csdn.net/qq_44157349/article/details/121523350