Java中Lambda表达式用法是什么

发布时间:2021-12-31 14:03:40 作者:柒染
来源:亿速云 阅读:97

本篇文章为大家展示了Java中Lambda表达式用法是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

Lambda

lambda是一个匿名函数,我们可以把lambda表达式理解为是一段可以传递的代码。

lambda表达式拆分为两部分

左侧:lambda 表达式的参数列表

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

语法格式一:无参数,无返回值

@Test
public void test(){
    // () -> System.out.println("Hello");
    Runnable a = new Runnable(){
     @Override
     public void run(){
        System.out.println("Hello")
    }
    };
    //等同于
    Runnable a1 = () -> System.out.println("Hello");
    a1.run();
}

语法格式二:有一个参数,无返回值(若只有一个参数 小括号可以省略不写)

@Test
public void test(){
    //Consumer被注解@FunctionalInterface的接口(函数式接口) 唯一抽象方法 void accept(T t);
    //左侧参数 -> 右侧执行体
    Consumer<String> con = (x) -> System.out.println(x);
                         // x -> System.out.println(x);
    con.accept("hahah");
}

语法格式三:有两个以上的参数,并且lambda体中有多条语句 (若lambda体中只有一条语句,return 和 大括号都可以省略不写)

@Test
public void test(){
    //Comparator被注解@FunctionalInterface的接口 举例抽象方法 int compare(T o1,T o2);
    Comparator<Integer> com = (x,y) -> {
      System.out.println("hhaha0");
      return (x < y) ? -1 : ((x == y) ? 0 : 1);
    };
    com.compare(1,2);
}

注意:lambda表达式的参数类型可以省略不写,因为jvm编译器可以从上下文推断出数据类型。即“类型推断”如果要在参数里面写数据类型,都要写上。

实例

实例1:

class Employee {
    private String name;
    private int age;
    private double salary;

    //省略 get and set and constructor

}
interface MyPredicate<T> {
    boolean test(T t);
}
public class Test{
    static List<Employee> list = Arrays.asList(
            new Employee("张三",10,1),
            new Employee("里斯",20,1),
            new Employee("王五",16,1),
            new Employee("二三",30,1)
    );
    public static List<Employee> filterEmployee(List<Employee> list,MyPredicate<Employee> mp){
        List<Employee> emps = new ArrayList<>();
        for (Employee employee : list) {
            if(mp.test(employee)){
                emps.add(employee);
            }
        }
        return emps;
 }
    @org.junit.Test
    public void test1(){
        //需要使用自定义的方法
        List<Employee> list2 = filterEmployee(list,(e) -> e.getAge() >= 15);
        list2.stream().map(Employee::getName).forEach(System.out::println);
    }
    @org.junit.Test
    public void test2(){
        //可以使用stream进行list集合的过滤  不使用自定义接口
        List<Employee> list2 = list.stream().filter((e) -> e.getAge() >= 15).collect(Collectors.toList());
        list2.stream().map(Employee::getName).forEach(System.out::println);
    }
}

实例2:

创建一个MyFun接口使用@FunctionalInterface注解,并创建一个抽象方法Integer getValue(Integer num);在Test类对变量进行某种操作。

@FunctionalInterface
interface MyFun{
    Integer getValue(Integer num);
}
public class Test{
    @org.junit.Test
    public void Test(){
        operation(100,num -> ++num);
    }
    /**
    * param1 num : 传入的整形数
    * param2 mf : 实现某种方式对 整形数 进行操作。
    **/
    public Integer operation(Integer num,MyFun mf){
        return mf.getValue(num);
    }
}
class Employee {
    private String name;
    private int age;
    private double salary;

    @Override
    public String toString() {
        return "["+this.name+","+this.getAge()+","+this.getSalary()+"]";
    }
    //省略 getter and setter  and constructor
}

public class Test {
    List<Employee> list = Arrays.asList(
            new com.bilibili.lambda.test1.Employee("张三",10,1),
            new com.bilibili.lambda.test1.Employee("里斯",20,1),
            new com.bilibili.lambda.test1.Employee("王五",16,1),
            new Employee("二三",30,1)
    );
    @org.junit.Test
    public void test(){
        Collections.sort(list,(e1,e2) -> {
            if(e1.getAge() == e2.getAge()){
                return e1.getName().compareTo(e2.getName());
            }else{
                //比较年龄大小
                return Integer.compare(e1.getAge(),e2.getAge());
            }
        });
        for (Employee e: list) {
            System.out.println(e);
        }
    }
}

四大核心函数式接口

 class Test{
    @org.junit.Test
    publilc void test(){
        happy(10000,(money)->System.out.println("happy消费"+money+"元"));
    }
    public void happy(double money,Consumer<double> con){
        con.accept(money);
    }
}

lambda方法引用

方法引用:若lambda体中的内同有方法已经实现了,我们可以使用“方法引用”

(可以理解为方法引用时lambda的另一种表现形式)

主要有三种语法格式:

class Test{
    //对象::实例方法名
    @org.junit.Test
    public void test(){
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("haha");
        Consumer<String> con2 = System.out::println;
        con2.accept("haha");
    }
    //类::静态方法名
    @org.junit.Test
    public void test2(){
        Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
        Comparator<Integer> com2 = Integer::compare;
        com.compare(1,2);
        com2.compare(1,2);
    }
    //类::实例方法名
    @org.junit.Test(){
        BiPredicate<String,String> bp = (x,y) -> x.equals(y);
        bp.test("a","a");
        BiPredicate<String,String> bp2 = String::equals;
    }
}

lambda构造器引用

格式:

CalssName::new

class Test{
    @org.junit.Test
    public void test(){
        Supplier<String> sup = () -> new String();
        //这里的构造器引用取决于 接口方法的参数 的个数。 此处函数式接口 T get(); 为无参抽象方法所以String在实例化时 也是实例化无参的构造方法  其他类也适用
        Supplier<String> sup2 = String::new;
        String str = sup2.get();
    }
}

上述内容就是Java中Lambda表达式用法是什么,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. java中Lambda表达式的用法
  2. java8之lambda表达式用法总结

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java lambda

上一篇:如何克隆MAC地址来绕过强制门户

下一篇:TeamViewer 14 for Mac是什么软件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》