专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 Lambda语法的格式

Lambda语法的格式

更新时间:2022-06-07 09:58:09 来源:赢咖4 浏览412次

赢咖4小编来告诉大家Lambda语法的格式。

//左侧: Lambda 表达式的参数列表

//右侧: Lambda 表达式中所需执行的功能,即Lambda体

package com.lm; 
import org.junit.Test; 
import java.util.*;
import java.util.function.Consumer;
//左侧: Lambda 表达式的参数列表
//右侧: Lambda 表达式中所需执行的功能,即Lambda体
public class TestLambda7 {  
    // 语法格式一: 无参数无返回值
    // ()->  System.out.println("Hello world");
    @Test
    public void test1() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello world");
            }
        };
        r.run();
        System.out.println("--------------------------");
        Runnable r1 = ()->  System.out.println("Hello world");
        r1.run();
    } 
    // 语法格式二: 有一个参数,无有返回值
    // (x) -> System.out.println(x)
    @Test
    public void test2() {
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("hello world");
    } 
    // 语法格式三: 如果只有有一个参数,小括号可以省略不写
    @Test
    public void test3() {
        Consumer<String> con = x -> System.out.println(x);
        con.accept("hello world");
    } 
    // 语法格式四:有两个以上参数,有返回值,并且Lammbda 体中有多条语句
    //多条语句用大括号
    @Test
    public void test4() { 
        Comparator<Integer> com = (x,y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x,y);
        };
        Integer result = com.compare(1,2);  //比大小
        System.out.println(result);
    } 
    // 语法格式五:有两个以上参数,有返回值,并且Lammbda 体中只有一条语句,
    //  return和大括号可以省略不写
    //   Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
    @Test
    public void test5() {
        Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
        Integer result = com.compare(1,2);  //比大小
        System.out.println(result);
    }  
    // 语法格式六:
    //  Lammbda 表达式参数列表的数据类型可以省略不写,JVM编译器会通过上下文推断出数据类型,即“类型推断”
    //  Comparator<Integer> com = (Integer x,Integer y) -> Integer.compare(x,y);
    //  Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
    //  Comparator<Integer> com 这里指定了数据类型
    @Test
    public void test6() {
        Comparator<Integer> com = (Integer x,Integer y) -> Integer.compare(x,y);
        Integer result = com.compare(1,2);  //比大小
        System.out.println(result);
    } 
    //上下文推断数据类型
    @Test
    public void test7() {
        //由后面推断数据类型
        String[] strs = {"aaa","bbb","ccc"}; 
        //这种情况就没法推断数据类型
//        String[] strs1;
//        strs1 = {"aaa","bbb","ccc"}; 
        //后在<>类型由前面推断出是String类型
        List<String> list = new ArrayList<>(); 
        //这里HashMap不带数据类型,是由下面的方法参数推断出来的,这里可以不写,这是jdk1.8新特性,JDK1.7就会出错
        showMap(new HashMap<>()); 
    }
    public void showMap (Map<String,Integer> map){
        System.out.println(map);
    };  
}

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>