Introduction to Java 8 Lambda Expressions

本文介绍了Java 8中的Lambda表达式,它是Java向函数式编程迈进的关键特性。Lambda表达式使得传递功能给其他方法的方式更加简洁和易读,减少了匿名类的使用。文章详细解释了Lambda表达式的语法、例子以及它们如何与函数式接口关联,帮助理解其在Java类型系统中的作用。
摘要由CSDN通过智能技术生成

Introduction to Java 8 Lambda Expressions

Lambda expressions were introduced in Java 8 and they became the talk of the town as soon as they arrived.

Java has evolved a lot with time. It has incorporated new ideas and programming paradigms as and when necessary. That is the main reasons why It is still the most used language worldwide.

Functional programming was on the rise when Lambda expressions were introduced in Java 8.

Java embraced functional programming by introducing several new features in Java 8 like Lambda Expressions, Stream API, Optional etc.

In this article, you’ll learn what lambda expression is, how it works under the hood, and how to use it effectively in your programs.

The need for lambda expressions

Java is a pure object oriented programming language. Everything in Java is an Object with the exception of primitive types.

Java是一种纯粹的面向对象的编程语言。Java中所有的内容都是对象,原始类型除外。

You can’t define top level functions (functions that don’t belong to a class) in Java. You can’t pass a function as an argument, or return a function from another function.

您无法在Java中定义顶级函数(不属于类的函数)。您不能将函数作为参数传递,也不能从另一个函数返回函数。

So, what’s the alternative?

Before lambda expressions were introduced, Developers used to use Anonymous class syntax for passing functionality to other methods or constructors.

在引入lambda表达式之前,开发人员曾经使用匿名类语法将功能传递给其它方法或构造函数。

Let’s see an example of anonymous class syntax. Consider the following Employee class -

class Employee {
   
    private String name;
    private int age;

    // Constructor, Getters, Setters (Omitted for brevity)
}

Now, To sort a list of employees, we usually pass a custom comparator to the List.sort() method as described in the following example -

现在,为了对员工列表进行排序,我们通常将自定义比较器传递给List.sort()方法,如以下示例中所述-

List<Employee> employees = Arrays.asList(new Employee("Foo", 21),
        new Employee("Bar", 25));

// Sort employees based on their age by passing an anonymous comparator.
employees.sort(new Comparator<Employee>() {
   
    @Override
    public int compare(Employee e1, Employee e2) {
   
        return e1.getAge() - e2.getAge();
    }
});

In the above example, we wanted to pass a single compare() functionality to the sort() method for comparing two Employees.

在上面的示例中,我们希望将单个compare()功能传递给sort()方法,以比较两个Employees。

For doing this, we had to create an anonymous

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值