java8新特性专题之二、lambda基础语法

几种基础语法

一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
箭头操作符将 Lambda 表达式拆分成两部分:

  左侧:Lambda 表达式的参数列表
  右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体

语法 

  1. 语法格式一:无参数,无返回值
        () -> System.out.println("Hello Lambda!");
 
  2. 语法格式二:有一个参数,并且无返回值
        (x) -> System.out.println(x)
 
 3. 语法格式三:若只有一个参数,小括号可以省略不写
        x -> System.out.println(x)
 
  4. 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
 
  5. 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
 
  6. 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
        (Integer x, Integer y) -> Integer.compare(x, y);

Lambda 表达式需要“函数式接口”的支持

  函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
             可以检查是否是函数式接口
@FunctionalInterface
public interface MyFun {
    public Integer getValue(Integer xy);
}
public static Integer getFunValue(Integer num,MyFun fun){
        return fun.getValue(num);
    }
public static  void m2(){
        System.out.println(getFunValue(12,x-> {return x + 10;}));

    }

四大核心函数式接口

  1. 消费性接口:
  public static void test1(){
        consum(10,(x)->System.out.println("消费了: "+x));
    }

    //Consumer<T> 消费型接口 :
    public static void consum(int m, Consumer<Integer> consumer){
        consumer.accept(m);
    }
  1. 供给型接口
public static void test2(){
        int value = supplier(11,()-> 11*11);
        System.out.println(value);
    }

    //供给型接口
    public static int supplier(int n, Supplier<Integer> supplier){
        return supplier.get();
    }
  1. 函数型接口
   public static void test3(){
        function("test",(x)->{return x.length();});
    }
    //函数型接口
    public static Integer  function(String str, Function<String,Integer> function){
        return function.apply(str);
    }
  1. 断言型接口
public static  void test4(){
        boolean result = predicate("123qwe",(x)->x.equals("123qwe"));
        System.out.println(result);
    }
    //断言型接口
    public static boolean predicate(String str, Predicate<String> predicate){
        return predicate.test(str);
    }

例子

package com.zs.boot.controller;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
 
import org.junit.Test;
 
/*
 * 一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
 *                             箭头操作符将 Lambda 表达式拆分成两部分:
 * 
 * 左侧:Lambda 表达式的参数列表
 * 右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
 * 
 * 语法格式一:无参数,无返回值
 *         () -> System.out.println("Hello Lambda!");
 * 
 * 语法格式二:有一个参数,并且无返回值
 *         (x) -> System.out.println(x)
 * 
 * 语法格式三:若只有一个参数,小括号可以省略不写
 *         x -> System.out.println(x)
 * 
 * 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
 *        Comparator<Integer> com = (x, y) -> {
 *            System.out.println("函数式接口");
 *            return Integer.compare(x, y);
 *        };
 *
 * 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
 *         Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
 * 
 * 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
 *         (Integer x, Integer y) -> Integer.compare(x, y);
 *           例如:jdk1.8中
 *           //下面也是类型推断
 *              List<String> list = new ArrayList<>();
 *
 *           //直接这样调用show,这样也是类型推断
 *           show(new HashMap<>());
 *             public void show(Map<String, Integer> map){
 *             
 *           }
 * 
 * 上联:左右遇一括号省
 * 下联:左侧推断类型省
 * 横批:能省则省
 * 
 * 二、Lambda 表达式需要“函数式接口”的支持
 * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
 *              可以检查是否是函数式接口
 */
public class TestLambda2 {
    
    @Test
    public void test1(){
        int num = 0;//jdk 1.7 前,必须是 final。
        // 因为在JDK8之前,如果我们在匿名内部类中需要访问局部变量,那么这个局部变量必须用final修饰符修饰。
        
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World!" + num);
            }
        };
        r.run();
        
        System.out.println("-------------------------------");
        
        Runnable r1 = () -> System.out.println("Hello Lambda!");
        r1.run();
    }
    
    @Test
    public void test2(){
        Consumer<String> con = x -> System.out.println(x);
        con.accept("helloworld!");
    }
    
    @Test
    public void test3(){
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
    }
    
    @Test
    public void test4(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
    }
 
    
    //需求:对一个数进行运算
    @Test
    public void test6(){
        Integer num = operation(100, (x) -> x*x);
        System.out.println(num);
        
        System.out.println(operation(200, (y) -> y + 200));
    }
    
    public Integer operation(Integer num, MyFun mf){
        return mf.getValue(num);
    }
 
    @FunctionalInterface
    public interface MyFun
        public Integer getValue(Integer num);
    }
}

例子

package com.atguigu.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.junit.Test;

/*
 * Java8 内置的四大核心函数式接口
 * 
 * Consumer<T> : 消费型接口
 *         void accept(T t);
 * 
 * Supplier<T> : 供给型接口
 *         T get(); 
 * 
 * Function<T, R> : 函数型接口
 *         R apply(T t);
 * 
 * Predicate<T> : 断言型接口
 *         boolean test(T t);
 * 
 */
public class TestLambda3 {
    
    //Predicate<T> 断言型接口:
    @Test
    public void test4(){
        List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
        List<String> strList = filterStr(list, (s) -> s.length() > 3);
        
        for (String str : strList) {
            System.out.println(str);
        }
    }
    
    //需求:将满足条件的字符串,放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> strList = new ArrayList<>();
        
        for (String str : list) {
            if(pre.test(str)){
                strList.add(str);
            }
        }
        
        return strList;
    }
    
    //Function<T, R> 函数型接口:
    @Test
    public void test3(){
        String newStr = strHandler("\t\t\t 我大尚硅谷威武   ", (str) -> str.trim());
        System.out.println(newStr);
        
        String subStr = strHandler("我大尚硅谷威武", (str) -> str.substring(2, 5));
        System.out.println(subStr);
    }
    
    //需求:用于处理字符串
    public String strHandler(String str, Function<String, String> fun){
        return fun.apply(str);
    }
    
    //Supplier<T> 供给型接口 :
    @Test
    public void test2(){
        List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
        
        for (Integer num : numList) {
            System.out.println(num);
        }
    }
    
    //需求:产生指定个数的整数,并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();
        
        for (int i = 0; i < num; i++) {
            Integer n = sup.get();
            list.add(n);
        }
        
        return list;
    }
    
    //Consumer<T> 消费型接口 :
    @Test
    public void test1(){
        happy(10000, (m) -> System.out.println("你们刚哥喜欢大宝剑,每次消费:" + m + "元"));
    } 
    
    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }
}

参考:https://www.jianshu.com/p/d70300190435 

posted @ 2022-03-05 22:37  程序员小明1024  阅读(40)  评论(0编辑  收藏  举报