Lambda Expressions: Introduction, Syntax, and Usage

insert image description here

Lambda expressions are an important feature introduced in Java 8, which allows developers to write functional code in a more concise manner. In this article, we will deeply explore the concept, syntax and usage of Lambda expressions, and provide code demonstrations for each instance, while comparing the differences and advantages with traditional methods.

1. Overview of Lambda expressions

Lambda expressions are anonymous functions that are primarily used to represent simple behaviors or blocks of code that can be passed into other functions when needed. Lambda expression can be regarded as an instance of functional interface, which consists of three parts: parameter list, arrow symbol and expression body. Here is an example of a simple Lambda expression:

() -> System.out.println("Hello, World!");

In this example, the Lambda expression contains an empty parameter list, the arrow symbol "->", and an expression body that outputs "Hello, World!". It can be executed by invoking the functional interface of the Lambda expression.

2. Lambda expression syntax

The syntax of a lambda expression is very simple, it consists of three parts: parameter list, arrow notation and expression body. Following is the syntax of Lambda expression:

(parameters) -> expression

or

(parameters) -> {
    
     statements; }

Among them, the parameter list can be empty, contain one parameter, or contain multiple parameters. If there are multiple parameters, the parameters need to be separated by commas. The expression body can be a simple expression or a block of code.

When using the Java language, Lambda expressions also consist of three key parts:

Parameter list : Specifies the parameters accepted by the Lambda function. There can be zero or more parameters, separated by commas and placed in parentheses.

Arrow symbol : The arrow symbol "->" is used to separate the parameter list and expression body. It means to map the given parameters into the expression body for calculation.

Expression body : Specifies the code block executed by the Lambda function, which can be any valid expression or statement block.

Here's a simple example showing an example of using a Lambda expression to sort an array of strings:

// 对字符串数组进行排序
String[] myArray = {
    
    "hello", "world", "lambda", "expression"};

// 使用Lambda表达式定义排序规则
Arrays.sort(myArray, (String str1, String str2) -> str1.compareTo(str2));

// 输出排序后的结果
System.out.println(Arrays.toString(myArray));

In this example, a Lambda expression is used as the Comparator implementation passed to the Arrays.sort method. The Lambda expression (String str1, String str2) -> str1.compareTo(str2) specifies the collation, it accepts two parameters str1 and str2, and returns the result of their comparison. This means that the string array will be sorted alphabetically.

Note that Lambdaexpressions need to be implemented using a functional interface. A functional interface is an interface with only one abstract method, which can be Lambdaimplemented by an expression. Java 8 provides many built-in functional interfaces such as Comparator, , Runnableand Functionetc.

3. Lambda expression usage

The main use of lambda expressions is as a functional interface

Some demos are provided;

1. Traverse the list and output each element

List<String> list = Arrays.asList("apple", "banana", "orange");

// 使用Lambda遍历列表
list.forEach(item -> System.out.println(item));

// 常规写法
for (String item : list) {
    
    
    System.out.println(item);
}

2. Filter the even numbers in the list and return a new list

List list = Arrays.asList(1, 2, 3, 4, 5, 6);

// Use Lambda to filter even numbers

List<Integer> evenList = list.stream().filter(num -> num % 2 == 0).collect(Collectors.toList());
System.out.println(evenList);

// 常规写法
List<Integer> evenList2 = new ArrayList<>();
for (Integer num : list) {
    
    
    if (num % 2 == 0) {
    
    
        evenList2.add(num);
    }
}
System.out.println(evenList2);

3. Convert the string to uppercase and return a new list

List<String> list = Arrays.asList("apple", "banana", "orange");

// 使用Lambda将字符串转换为大写


List<String> upperList = list.stream().map(str -> str.toUpperCase()).collect(Collectors.toList());
System.out.println(upperList);

// 常规写法
List<String> upperList2 = new ArrayList<>();
for (String str : list) {
    
    
    upperList2.add(str.toUpperCase());
}
System.out.println(upperList2);

4. Calculate the sum of all elements in the list

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

// 使用Lambda计算列表元素总和
int sum = list.stream().reduce(0, (a, b) -> a + b);
System.out.println(sum);

// 常规写法
int sum2 = 0;
for (Integer num : list) {
    
    
    sum2 += num;
}
System.out.println(sum2);

5. Convert the elements in the list into key-value pairs and put them into the Map

List<String> list = Arrays.asList("apple", "banana", "orange");

// 使用Lambda将列表中的元素转换为键值对并放入Map中
Map<String, Integer> map = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
System.out.println(map);

// 常规写法
Map<String, Integer> map2 = new HashMap<>();
for (String str : list) {
    
    
    map2.put(str, str.length());
}
System.out.println(map2);

6. Filter the elements in the collection

// 使用Lambda表达式筛选出小于10的数字
List<Integer> numbers = Arrays.asList(1, 5, 10, 15);
List<Integer> filteredNumbers = numbers.stream()
                                        .filter(n -> n < 10)
                                        .collect(Collectors.toList());

// 传统写法
List<Integer> filteredNumbers = new ArrayList<>();
for (Integer n : numbers) {
    
    
    if (n < 10) {
    
    
        filteredNumbers.add(n);
    }
}

7. Mapping in collections

// 使用Lambda表达式将字符串转换为它们的长度
List<String> words = Arrays.asList("apple", "banana", "orange");
List<Integer> wordLengths = words.stream()
                                 .map(s -> s.length())
                                 .collect(Collectors.toList());

// 传统写法
List<Integer> wordLengths = new ArrayList<>();
for (String s : words) {
    
    
    wordLengths.add(s.length());
}

8. Sort the elements in the collection

// 使用Lambda表达式将集合中的元素按字母顺序排序
List<String> words = Arrays.asList("apple", "banana", "orange");
Collections.sort(words, (s1, s2) -> s1.compareTo(s2));

// 传统写法
List<String> words = Arrays.asList("apple", "banana", "orange");
Collections.sort(words, new Comparator<String>() {
    
    
    public int compare(String s1, String s2) {
    
    
        return s1.compareTo(s2);
    }
});

9. Perform multiple actions

// 使用Lambda表达式执行多个操作
List<String> words = Arrays.asList("apple", "banana", "orange");
words.stream()
     .filter(s -> s.startsWith("a"))
     .map(s -> s.toUpperCase())
     .forEach(System.out::println);

// 传统写法
List<String> words = Arrays.asList("apple", "banana", "orange");
for (String s : words) {
    
    
    if (s.startsWith("a")) {
    
    
        System.out.println(s.toUpperCase());
    }
}

10. Sort an array of integers

//传统写法:

int[] arr = {
    
    3, 1, 4, 1, 5, 9, 2, 6, 5};
Arrays.sort(arr, new Comparator<Integer>() {
    
    
    public int compare(Integer a, Integer b) {
    
    
        return a - b;
    }
});
//Lambda写法:

int[] arr = {
    
    3, 1, 4, 1, 5, 9, 2, 6, 5};
Arrays.sort(arr, (a, b) -> a - b);

Description: This example shows how to use Lambda expressions to sort an array of integers. In traditional writing, we need to define a class that implements the Comparator interface and pass it to the Arrays.sort() method when sorting. In the Lambda writing method, we only need to write a simple line of code to complete the same operation.

11 Use the Stream API to filter collection elements


//传统写法:

List<String> list = Arrays.asList("apple", "banana", "cherry", "date");
List<String> filteredList = new ArrayList<>();
for (String s : list) {
    
    
    if (s.startsWith("a")) {
    
    
        filteredList.add(s);
    }
}
//Lambda写法:

List<String> list = Arrays.asList("apple", "banana", "cherry", "date");
List<String> filteredList = list.stream()
    .filter(s -> s.startsWith("a"))
    .collect(Collectors.toList());

Description: This example shows how to use Lambda expression and Stream API to filter a list of strings. In the traditional writing method, we need to manually traverse the entire collection and filter out eligible elements, but in the Lambda writing method, we can use the stream() method to convert the collection into a stream, and use the filter() method to filter the stream.

12. Using Lambda Expressions as Method Parameters

//传统写法:

public static void operate(int a, int b, Operation operation) {
    
    
    System.out.println(operation.operate(a, b));
}

interface Operation {
    
    
    int operate(int a, int b);
}

operate(2, 3, new Operation() {
    
    
    public int operate(int a, int b) {
    
    
        return a + b;
    }
});
//Lambda写法:

public static void operate(int a, int b, IntBinaryOperator operator) {
    
    
    System.out.println(operator.applyAsInt(a, b));
}

operate(2, 3, (a, b) -> a + b);

Description: This example shows how to use Lambda expressions as method parameters. In traditional writing, we need to define a class that implements a certain interface and pass it to the method when calling the method. In Lambda writing, we can directly write Lambda expressions as parameters when calling methods, thus omitting additional class definitions.

13. Using Lambda Expressions as Variables

//传统写法:

public static void printMessage(String message) {
    
    
    System.out.println(message);
}

printMessage("Hello, world!");
//Lambda写法:

Consumer<String> printer = (message) -> System.out.println(message);
printer.accept("Hello, world!");

Description: This example shows how to use Lambda expressions to define an implementation of a functional interface and use it as a variable. In traditional writing, we need to define a method and pass parameters when calling it. In Lambda writing, we can first define a functional interface, then use Lambda expressions to create its implementation, and assign it to a variable.

4. Advantages and disadvantages of Lambda expression

Lambda expressions have the following advantages :

Conciseness: Using Lambda expressions can save a lot of boilerplate code.
Flexible: Lambda expressions can be defined at runtime and created when needed.
Easy to read: The syntax of Lambda expressions is straightforward and easy to understand.

Lambda expressions also have the following disadvantages:

Readability: Excessive use of Lambda expressions may reduce the readability of the code.
Performance: Lambda expressions may perform slightly worse than normal methods. But in most scenarios, this gap is negligible.

Guess you like

Origin blog.csdn.net/qq_42055933/article/details/130158444