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