【Java】Effective Lambda Expressions in Java(一)

简介: 【Java】Effective Lambda Expressions in Java

原文

Effective Lambda Expressions in Java | by Bubu Tripathy | Medium

Introductory

Lambda expressions were introduced in Java 8 to allow functional programming in Java. They are a concise way to express functions that can be used as data and provide a more functional approach to programming. Lambda expressions can be used in a variety of ways, from simple expressions to complex functions. In this article, we will discuss 20 best practices of using lambda expressions in Java with examples for each.

Lambda 表达式在 Java 8 中引入,允许在 Java 中进行函数式编程。Lambda表达式是表达可用作数据的函数的一种简洁方式,并为编程提供了一种功能性更强的方法。Lambda表达式的使用方式多种多样,从简单的表达式到复杂的函数。在本文中,我们将讨论在Java中使用lambda表达式的20个最佳实践,并分别举例说明。

Use Lambda expressions to create functional Interfaces 使用Lambda表达式创建功能接口

A functional interface is an interface that contains a single abstract method. Functional interfaces are used extensively in Java to represent functions and Lambdas.

功能接口是一个包含单个抽象方法的接口。功能接口在Java中广泛用于表示函数和Lambdas。

When using Lambda expressions to create functional interfaces, the Lambda expression is used to define the implementation of the abstract method. The Lambda expression takes the same parameters as the abstract method, and returns a value that represents the result of the method.

当时用Lambda 表达式创建功能接口的时候,Lambda 表达式用于定义抽象方法实现。Lambda 表达式接受和抽象方法相同的参数,并且返回代表方法结果的值。

Here is an example of using Lambda expressions to create a functional interface for a calculator:

下面是使用Lambda 表达式来创建功能接口计算器的案例:


@FunctionalInterface  
interface Calculator {  
    int calculate(int a, int b);  
}  
public class LambdaDemo {  
    public static void main(String[] args) {  
        Calculator add = (a, b) -> a + b;  
        Calculator subtract = (a, b) -> a - b;  
        System.out.println("10 + 5 = " + add.calculate(10, 5));  
        System.out.println("10 - 5 = " + subtract.calculate(10, 5));  
    }  
}

In this example, we are using a Lambda expression to define the implementation of the calculate() method of the Calculator interface. The calculate() method takes two integer values as input (a and b), and returns an integer value representing the result of the calculation.

在这个例子中,我们使用Lambda 表达式定义Calculator 接口的 calculate() 方法的实现。calculate() 方法接收两个整型参数作为输入(a 和 b),并且返回一个整型结果代表计算结果

Note that in this example, we are using the @FunctionalInterface annotation to indicate that the Calculator interface is a functional interface. This annotation is not strictly necessary, but it can help to clarify the intent of the interface.

注意在这个例子中我们使用了 @FunctionalInterface  注解指定在 Calculator 接口的接口方法上面。这个注解严格上来来说是非必要的, 但它有助于明确界面的意图。

Use the right syntax for Lambda Expressions 为Lambda表达式使用正确的语法

When using Lambda expressions in Java, it is important to use the correct syntax for defining and using them. The syntax of a Lambda expression consists of three parts: the parameter list, the arrow operator, and the body.

在Java中使用Lambda表达式, 使用正确的语法定义和使用它们非常重要的。Lambda表达式的语法由三部分组成:参数列表箭头操作符主体

The parameter list [specifies] the input parameters that the Lambda expression will take. If there are no parameters, an empty parameter list must still be specified, as shown here:

参数列表指定了Lambda表达式将使用的输入参数,如果没有任何参数,一个空的参数化列表依然必须被指定,它的表现形式如下:


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

The arrow operator separates the parameter list from the body of the Lambda expression. The arrow operator can be either a hyphen and greater-than symbol (->), or the word “goes to” written as an equals sign followed by a greater-than symbol (=>).

箭头操作符将参数列表与Lambda表达式的主体分开,箭头运算符可以是-字符和大于号组合(->),也可以是等号和大于号组合(=>)。


// hyphen and greater-than symbol  
x -> x * x


// equals sign followed by a greater-than symbol  
(x, y) => x + y

The body of the Lambda expression specifies the behavior of the expression. The body can be a single expression, or a block of statements enclosed in braces. If the body is a single expression, the braces are optional.

Lambda 表达式的主体指定表达式的行为,主题可以是一个单独的表达式,也可以是用大括号括起来的语句块,如果主体是单个表达式,则大括号是可选的。

函数表达式


// single expression  
x -> x * x

语句块


// block of statements  
(x, y) -> {  
    int sum = x + y;  
    System.out.println("The sum is: " + sum);  
}

It is also important to use the correct type for Lambda expressions when they are assigned to variables or parameters. When a Lambda expression is assigned to a variable or parameter, the type of the variable or parameter must be a functional interface that is compatible with the Lambda expression.

当Lambda表达式设置变量或者参数的时候,使用正确的类型也是十分重要。当一个Lambda 表达式设置了变量或者参数,变量或参数必须是与Lambda表达式兼容的功能接口

For example, the following Lambda expression:

比如下面这个函数表达式的例子:


(x, y) -> x + y

can be assigned to a variable of type IntBinaryOperator:

这里只能够设置变量类型为 IntBinaryOperator


IntBinaryOperator add = (x, y) -> x + y;

Use Lambda expressions to implement Functional Programming 使用 Lambda 表达式实现函数式编程

Functional programming is a programming paradigm that emphasizes the use of functions and functional composition to solve problems. In Java, Lambda expressions can be used to implement functional programming by creating and using functions as first-class objects.

函数式编程是一种编程范式,强调使用函数和函数组合来解决问题。在Java中,可以使用Lambda表达式来实现函数式编程,将函数作为头等对象来创建和使用。

Functions in functional programming are defined by their behavior, rather than their implementation. This means that a function can be treated as an object, and passed around as a parameter or returned as a result. This is where Lambda expressions come in — they allow us to define functions as expressions, and pass them around as objects.

函数式编程当中行为是通过具体行为而不是实现定义的,也就是说函数可以是对象,并且把参数传递作为结果返回。Lambda表达式的强大之处就在于此,可以把函数作为表达式,并且把对应的对象进行传递。

Here is an example of using Lambda expressions to implement functional programming in Java:

下面是使用Lambda表达式使Java实现函数式编程。


public class FunctionalProgrammingDemo {  
    public static void main(String[] args) {  
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);  
        numbers.stream()  
            .filter(n -> n % 2 == 0)  
            .map(n -> n * n)  
            .forEach(System.out::println);  
    }  
}

In this example, we are using Lambda expressions to implement functional programming in Java. The code first creates a list of integers, and then uses a stream to process the list using functional operations.

在本示例中,我们使用Lambda表达式在Java中实现函数式编程。代码首先创建一个整数列表,然后使用stream的函数式操作来处理该列表。

The filter() operation uses a Lambda expression to define a predicate that filters out all odd numbers from the list. The map() operation uses another Lambda expression to define a function that squares each even number in the list. Finally, the forEach() operation uses a method reference to print each squared even number to the console.

filter() 操作使用 Lambda 表达式定义一个predicatepredicate中定义了过滤列表所有奇数的操作,map() 操作使用另一个Lambda表达式定义一个函数,该函数将列表中的每个元素求平方,最后使用 forEach 的方式,把每个处理之后的数据打印出来。

By using Lambda expressions to implement functional programming, you can create more expressive and modular code, and solve problems in a more concise and efficient way. Lambda expressions provide a powerful and flexible way to implement functional programming in Java and are a key feature of the Stream API in Java 8 and later versions.

使用函数表达式实现函数式编程,你可以创建更多更具表现力和模块化的代码,解决问你也会更加的简单高效,Lambda表达his提供一个强大并且流畅的方法在Java中实现函数式编程,这是Java 8及更高版本中流API的关键特性。

Use Lambda expressions to create Anonymous Classes 使用 Lambda 表达式创建匿名类

Anonymous classes are often used in Java to create objects with a specific behavior, such as event listeners or runnable tasks.

在Java中,匿名类通常用于创建具有特定行为的对象,如事件监听器或可运行任务。

Lambda expressions can be used to create anonymous classes in Java. When using Lambda expressions to create anonymous classes, the Lambda expression is used to define the behavior of the anonymous class.

Lambda表达式可用于在Java中创建匿名类。使用Lambda表达式创建匿名类时,Lambda表达式用于定义匿名类的行为。

Here is an example of using Lambda expressions to create an anonymous class that implements the Runnable interface:

下面是一个使用Lambda表达式创建一个实现Runnable接口的匿名类的示例:


public class AnonymousClassDemo {  
    public static void main(String[] args) {  
        Runnable runnable = () -> {  
            System.out.println("Hello from anonymous class!");  
        };  
        Thread thread = new Thread(runnable);  
        thread.start();  
    }  
}

In this example, we are using a Lambda expression to create an anonymous class that implements the Runnable interface. The code first defines a Lambda expression that simply prints a message to the console. This Lambda expression is then used to create an anonymous class that implements the Runnable interface. Finally, the anonymous class is passed to a Thread object and started.

在这个案例中,我们通过Lambda表达式创建Runnable的匿名类,代码首先定义了一个Lambda表达式,该表达式简单地向控制台打印一条消息。然后使用该Lambda表达式创建一个实现Runnable接口的匿名类。最后,匿名类被传递给Thread对象并启动。

Note that in this example, we are using a Lambda expression with a block of statements enclosed in braces. This is because the Runnable interface has a single abstract method, run(), that takes no arguments and returns no value. Therefore, the Lambda expression must define the behavior of the run() method using a block of statements.

请注意,在本示例中,我们使用的是一个Lambda表达式,其中的语句块用大括号括起来。这是因为Runnable接口只有一个抽象方法run(),它不需要参数也不返回值。因此,Lambda表达式必须使用语句块来定义run()方法的行为。

Use Lambda expressions to create Event Listeners 使用 Lambda 表达式创建事件监听器

Event listeners are used in Java to handle events that occur in a user interface or other system. Events can include things like button clicks, mouse movements, and keyboard inputs.

Java中的事件监听器用于处理用户界面或其他系统中发生的事件。

事件包括按钮点击、鼠标移动和键盘输入等。

When using Lambda expressions to implement event listeners, the Lambda expression is used to define the behavior that should be executed when the event occurs. The Lambda expression takes an event object as input, and performs some action based on the event.

当我们使用Lambda表达式实现事件监听器,通常需要用于定义事件发生时应执行的行为。Lambda表达式接收一个事件对象作为输入,并且根据事件的执行某些操作。

Here is an example of using Lambda expressions to implement an event listener for a button click:

下面是一个使用 Lambda 表达式实现按钮点击事件监听器的示例:


public class ButtonDemo {  
    public static void main(String[] args) {  
        JButton button = new JButton("Click me!");  
        button.addActionListener(event -> System.out.println("Button clicked!"));  
        JFrame frame = new JFrame();  
        frame.add(button);  
        frame.pack();  
        frame.setVisible(true);  
    }  
}

In this example, we are using a Lambda expression to define the behavior that should be executed when the button is clicked. The addActionListener() method of the JButton class takes a ActionListener object as input, which is implemented as a Lambda expression in this case. The Lambda expression simply prints a message to the console when the button is clicked.

在本示例中,我们使用Lambda表达式来定义点击按钮时应执行的行为。JButton类的addActionListener()方法将ActionListener对象作为输入,在本例中以Lambda表达式的形式实现。当按钮被点击时,Lambda表达式简单地向控制台打印一条消息。

Note that in this example, we are using the “arrow” notation (->) to separate the parameter list from the body of the Lambda expression. The parameter list consists of a single event object, which represents the button click event. The body of the Lambda expression simply prints a message to the console.

请注意,在本例中,我们使用了 "箭头 "符号 (->) 来分隔参数列表和 Lambda 表达式的主体。参数列表由单个字符串值组成,代表列表中的每个字符串。Lambda 表达式的主体只是将字符串打印到控制台。

Use Lambda expressions to Iterate over Collections 使用 Lambda 表达式遍历集合

Iterating over collections is a common operation in Java, and Lambda expressions can be used to simplify and streamline this process. When using Lambda expressions to iterate over collections, the Lambda expression is used to define the behavior that should be executed for each element in the collection.

在 Java 中,遍历集合是一种常见操作,而 Lambda 表达式可用于简化和精简这一过程。使用 Lambda 表达式遍历集合时,Lambda 表达式用于定义应针对集合中的每个元素执行的行为。

Here is an example of using Lambda expressions to iterate over a list of strings and print each string to the console:

下面是一个使用 Lambda 表达式遍历字符串列表并将每个字符串打印到控制台的示例:


List<String> strings = Arrays.asList("apple", "banana", "cherry");  
strings.forEach(s -> System.out.println(s));

In this example, we are using the forEach() method of the List interface to iterate over a list of strings. The forEach() method takes a Consumer object as input, which is implemented as a Lambda expression in this case. The Lambda expression simply prints each string to the console.

在本示例中,我们使用 List 接口的 forEach() 方法遍历字符串列表。forEach()方法将Consumer对象作为输入,在本例中以Lambda表达式的形式实现。Lambda 表达式简单地将每个字符串打印到控制台。

Note that in this example, we are using the “arrow” notation (->) to separate the parameter list from the body of the Lambda expression. The parameter list consists of a single string value, which represents each string in the list. The body of the Lambda expression simply prints the string to the console.

请注意,在本例中,我们使用了 "箭头 "符号 (->) 来分隔参数列表和 Lambda 表达式的主体。参数列表由单个字符串值组成,代表列表中的每个字符串。Lambda 表达式的主体只是将字符串打印到控制台。

Here is another example of using Lambda expressions to iterate over a map of key-value pairs and print each pair to the console:

下面是另一个使用 Lambda 表达式遍历键值对映射并将每一对键值对打印到控制台的示例:


Map<String, Integer> map = new HashMap<>();  
map.put("apple", 1);  
map.put("banana", 2);  
map.put("cherry", 3);


map.forEach((k, v) -> System.out.println(k + " -> " + v));

In this example, we are using the forEach() method of the Map interface to iterate over a map of key-value pairs. The forEach() method takes a BiConsumer object as input, which is implemented as a Lambda expression in this case. The Lambda expression takes two parameters, a key and a value, and simply prints each key-value pair to the console.

在本例中,我们使用 Map 接口的 forEach() 方法遍历键值对映射。forEach()方法将 BiConsumer 对象作为输入,在本例中是以 Lambda 表达式的形式实现的。

Lambda 表达式接收两个参数,一个键和一个值,并简单地将每个键值对打印到控制台。

Note that in this example, we are using the “arrow” notation (->) to separate the parameter list from the body of the Lambda expression. The parameter list consists of two values, a key and a value, which represent each key-value pair in the map. The body of the Lambda expression simply prints the key-value pair to the console.

请注意,在这个示例中,我们使用了 "箭头 "符号 (->) 来分隔参数列表和 Lambda 表达式的主体。参数列表由两个值(一个 key 和一个 value)组成,分别代表 map 中的每个键值对。Lambda 表达式的主体只是将键值对打印到控制台。

Use Lambda expressions to Filter Collections 使用 Lambda 表达式过滤集合

Filtering collections is a common operation in Java, and Lambda expressions can be used to simplify and streamline this process. When using Lambda expressions to filter collections, the Lambda expression is used to define a predicate that selects which elements in the collection should be included or excluded.

过滤集合是 Java 中的一种常见操作,而 Lambda 表达式可用于简化和精简这一过程。使用 Lambda 表达式过滤集合时,Lambda 表达式用于定义一个谓词,该谓词用于选择应包含或排除集合中的哪些元素。

Here is an example of using Lambda expressions to filter a list of integers and create a new list that contains only the even numbers:

下面是一个使用 Lambda 表达式过滤整数列表并创建一个只包含偶数的新列表的示例:


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);  
List<Integer> evenNumbers = numbers.stream()  
                                    .filter(n -> n % 2 == 0)  
                                    .collect(Collectors.toList());  
System.out.println(evenNumbers);

In this example, we are using the filter() method of the Stream interface to filter a list of integers. The filter() method takes a predicate as input, which is implemented as a Lambda expression in this case. The Lambda expression defines a predicate that tests whether a number is even or not by checking if its remainder is zero when divided by two.

在本例中,我们使用流接口的 filter() 方法过滤整数列表。filter() 方法将一个谓词作为输入,在本例中以 Lambda 表达式的形式实现。Lambda 表达式定义了一个谓词,该谓词通过检查一个数字除以 2 后的余数是否为零来检验该数字是否为偶数。

Note that in this example, we are using the “arrow” notation (->) to separate the parameter list from the body of the Lambda expression. The parameter list consists of a single integer value, which represents each element in the stream. The body of the Lambda expression is a boolean expression that defines the predicate.

请注意,在这个示例中,我们使用了 "箭头 "符号 (->) 来分隔参数列表和 Lambda 表达式的主体。参数列表由单个整数值组成,代表流中的每个元素。Lambda 表达式的主体是定义谓词的布尔表达式。

The filtered elements are then collected into a new list using the collect() method of the Stream interface, which takes a Collector object as input. The Collector object in this case is the toList() method of the Collectors class, which creates a new list of the filtered elements.

然后,使用流接口的 collect() 方法将过滤后的元素收集到一个新的列表中,该方法将收集器对象作为输入。本例中的收集器对象是收集器类的 toList() 方法,它将创建一个包含过滤元素的新列表。

Use Lambda expressions to Sort Collections 使用 Lambda 表达式对集合进行排序

Sorting is the process of arranging the elements of a collection in a specific order. In Java, collections can be sorted using the sorted() method of the Stream API.

排序是将集合中的元素按特定顺序排列的过程。在Java中,可以使用流API的 sorted() 方法对集合进行排序。

When using Lambda expressions to sort collections, the Lambda expression is used to define the order in which the elements should be sorted.

使用 Lambda 表达式对集合进行排序时,Lambda 表达式用于定义元素的排序顺序。

The Lambda expression takes two elements from the collection as input, and returns an integer value indicating their relative order.

Lambda 表达式将集合中的两个元素作为输入,并返回一个整数值,表示它们的相对顺序。

If the first element should come before the second element in the sorted collection, the Lambda expression returns a negative integer.

如果在排序集合中,第一个元素应在第二个元素之前,则 Lambda 表达式会返回一个负整数。

If the first element should come after the second element, the Lambda expression returns a positive integer. If the two elements are equal, the Lambda expression returns zero.

如果第一个元素位于第二个元素之后,则 Lambda 表达式返回一个正整数。如果两个元素相等,则 Lambda 表达式返回 0。

Here is an example of using Lambda expressions to sort a list of integers:

下面是一个使用 Lambda 表达式对整数列表进行排序的示例:


List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);  
List<Integer> sortedNumbers = numbers.stream().sorted().collect(Collectors.toList());

In this example, we are using a Lambda expression to sort the list of integers in ascending order. The sorted() method uses this Lambda expression to create a new stream that contains the elements of the original list in sorted order.

在这个示例中,我们使用 Lambda 表达式按升序对整数列表进行排序。

sorted()方法使用该Lambda表达式创建一个新的流,其中包含按排序顺序排列的原始列表元素。

Note that in this example, we are not explicitly defining a Lambda expression for the sorted() method. This is because the default behavior of the sorted() method is to sort the elements in natural order. However, you can also provide a custom Lambda expression to the sorted() method to define a custom sort order.

请注意,在这个示例中,我们没有为 sorted() 方法明确定义一个 Lambda 表达式。这是因为 sorted() 方法的默认行为是按自然顺序对元素进行排序。

不过,您也可以为 sorted() 方法提供自定义 Lambda 表达式,以定义自定义排序顺序。

Here is an example of using a Lambda expression to sort a list of strings in descending order:

下面是一个使用 Lambda 表达式对字符串列表进行降序排序的示例:


List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");  
List<String> sortedWords = words.stream().sorted((a, b) -> b.compareTo(a)).collect(Collectors.toList());

In this example, we are using a Lambda expression to sort the list of strings in descending order. The Lambda expression takes two strings as input, and returns the result of comparing the second string to the first string using the compareTo() method of the String class.

在本例中,我们使用 Lambda 表达式对字符串列表进行降序排序。Lambda 表达式将两个字符串作为输入,并使用 String 类的 compareTo() 方法返回第二个字符串与第一个字符串的比较结果。

Use Lambda expressions to Map Collections

Mapping is the process of transforming one collection into another. In Java, collections can be mapped using the map() method of the Stream API.

Map是将一个集合转换成另一个集合的过程。在 Java 中,可以使用流 API 的 map() 方法对集合进行映射。

When using Lambda expressions to map collections, the Lambda expression is used to define the transformation that should be applied to each element in the collection. The Lambda expression takes an element from the collection as input and returns a new value that represents the transformed element.

使用 Lambda 表达式映射集合时,Lambda 表达式用于定义应用于集合中每个元素的转换。Lambda 表达式将集合中的元素作为输入,并返回一个代表转换后元素的新值。

Here is an example of using Lambda expressions to map a list of strings to a list of integers:


List<String> strings = Arrays.asList("1", "2", "3", "4", "5");  
List<Integer> integers = strings.stream().map(Integer::parseInt).collect(Collectors.toList());

In this example, we are using a Lambda expression to map the list of strings to a list of integers. The Lambda expression applies the parseInt() method of the Integer class to each string in the list, converting it to an integer value. The map() method then uses this Lambda expression to create a new stream that contains the transformed elements.

在本例中,我们使用 Lambda 表达式将字符串列表映射为整数列表。Lambda 表达式对列表中的每个字符串应用 Integer 类的 parseInt() 方法,将其转换为整数值。然后,map() 方法使用此 Lambda 表达式创建一个包含转换后元素的新流。

Note that in this example, we are using the method reference notation (::) to refer to the parseInt() method of the Integer class. This is a shorthand notation for a Lambda expression that simply calls a single method.

请注意,在本例中,我们使用方法引用符号(::)来引用 Integer 类的 parseInt() 方法。这是一个 Lambda 表达式的简写符号,只需调用一个方法即可。

Here is another example of using a Lambda expression to map a list of strings to a list of uppercase strings:

下面是另一个使用 Lambda 表达式将字符串列表映射为大写字符串列表的示例:


List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");  
List<String> uppercaseWords = words.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());

In this example, we are using a Lambda expression to map the list of strings to a list of uppercase strings. The Lambda expression applies the toUpperCase() method of the String class to each string in the list, converting it to an uppercase string. The map() method then uses this Lambda expression to create a new stream that contains the transformed elements.

在本例中,我们使用 Lambda 表达式将字符串列表映射为大写字符串列表。Lambda 表达式将 String 类的 toUpperCase() 方法应用于列表中的每个字符串,将其转换为大写字符串。然后,map() 方法使用此 Lambda 表达式创建一个包含转换后元素的新流。

Use Lambda expressions to Reduce Collections 使用 Lambda 表达式精简集合

Reducing is the process of applying an operation to all the elements of a collection to produce a single result. In Java, collections can be reduced using the reduce() method of the Stream API.

Reducing 是对集合中的所有元素进行操作以产生单一结果的过程。在 Java 中,可以使用流 API 的 reduce() 方法对集合进行还原。

When using Lambda expressions to reduce collections, the Lambda expression is used to define the operation that should be applied to each element in the collection. The Lambda expression takes two arguments as input: an accumulator and an element from the collection. The accumulator is the result of the previous operation, or an initial value if this is the first operation. The Lambda expression returns a new value that represents the result of applying the operation to the accumulator and the current element.

使用 Lambda 表达式还原集合时,Lambda 表达式用于定义应用于集合中每个元素的操作。Lambda 表达式将两个参数作为输入:累加器和集合中的一个元素。累加器是前一次操作的结果,如果是第一次操作,则是初始值。Lambda 表达式返回一个新值,该值代表对累加器和当前元素应用操作的结果。

Here is an example of using Lambda expressions to reduce a list of integers to a single sum:

下面是一个使用 Lambda 表达式将整数列表简化为单个和的示例:


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);  
int sum = numbers.stream().reduce(0, (a, b) -> a + b);

In this example, we are using a Lambda expression to reduce the list of integers to a single sum. The Lambda expression takes two integer values as input: an accumulator (initialized to zero in this case), and an element from the list. The Lambda expression adds the element to the accumulator, and returns the new value of the accumulator. The reduce() method then uses this Lambda expression to apply the operation to each element in the list, producing the final sum.

在本例中,我们使用 Lambda 表达式将整数列表还原为单个和。Lambda 表达式将两个整数值作为输入:一个累加器(本例中初始化为零)和列表中的一个元素。Lambda 表达式将元素加到累加器中,并返回_accumulator_的新值。然后,reduce() 方法使用此 Lambda 表达式对列表中的每个元素进行运算,得出最终总和。

Note that in this example, we are using the “arrow” notation (->) to separate the parameter list  from the body of the Lambda expression. The parameter list consists of two integer values: the accumulator and the current element from the list. The body of the Lambda expression adds the current element to the accumulator using the + operator.

请注意,在本例中,我们使用了 "箭头 "符号 (->) 来分隔参数列表和 Lambda 表达式的主体。参数列表由两个整数值组成:累加器和列表中的当前元素。Lambda 表达式的主体使用 + 运算符将当前元素添加到累加器中。

Here is another example of using a Lambda expression to reduce a list of strings to a single concatenated string:

下面是另一个使用 Lambda 表达式将字符串列表缩减为单个连接字符串的示例:


List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");  
String concatenated = words.stream().reduce("", (a, b) -> a + b);

In this example, we are using a Lambda expression to reduce the list of strings to a single concatenated string. The Lambda expression takes two string values as input: an accumulator (initialized to an empty string in this case), and an element from the list. The Lambda expression concatenates the element to the accumulator, and returns the new value of the accumulator. The reduce() method then uses this Lambda expression to apply the operation to each element in the list, producing the final concatenated string.

在本例中,我们使用 Lambda 表达式将字符串列表还原为单个连接字符串。Lambda 表达式将两个字符串值作为输入:一个累加器(本例中初始化为空字符串)和列表中的一个元素。Lambda 表达式将元素连接到累加器,并返回累加器的新值。然后,reduce() 方法使用此 Lambda 表达式对列表中的每个元素进行操作,生成最终的连接字符串。

Use Lambda expressions to Group Collections  使用 Lambda 表达式对集合进行分组

Grouping is the process of grouping the elements of a collection based on a common property or criterion. In Java, collections can be grouped using the groupingBy() method of the Collectors class.

分组是根据共同属性或标准对集合中的元素进行分组的过程。在 Java 中,可以使用 Collectors 类的 groupingBy() 方法对集合进行分组。

When using Lambda expressions to group collections, the Lambda expression is used to define the criterion that should be used to group the elements. The Lambda expression takes an element from the collection as input, and returns a value that represents the grouping criterion.

使用 Lambda 表达式对集合进行分组时,Lambda 表达式用于定义对元素进行分组的标准。Lambda 表达式将集合中的元素作为输入,并返回一个代表分组标准的值。

Here is an example of using Lambda expressions to group a list of words by their length:

下面是一个使用 Lambda 表达式按单词长度分组的示例:


List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");  
Map<Integer, List<String>> groups = words.stream().collect(Collectors.groupingBy(String::length));

In this example, we are using a Lambda expression to group the list of words by their length. The groupingBy() method uses this Lambda expression to create a map that groups the words by their length. The key of each entry in the map is an integer value representing the length of the words, and the value of each entry is a list of words with that length.

在本例中,我们使用 Lambda 表达式按单词长度对单词列表进行分组。groupingBy() 方法使用此 Lambda 表达式创建一个按单词长度分组的映射。映射中每个条目的键是代表单词长度的整数值,每个条目的值是具有该长度的单词列表。

Note that in this example, we are using the method reference notation (::) to refer to the length() method of the String class. This is a shorthand notation for a Lambda expression that simply calls a single method.

请注意,在本例中,我们使用方法引用符号(::)来引用 String 类的 length() 方法。这是简单调用单个方法的 Lambda 表达式的速记符号。

Here is another example of using a Lambda expression to group a list of employees by their department:

下面是另一个使用 Lambda 表达式按部门对员工列表进行分组的示例:


List<Employee> employees = Arrays.asList(  
    new Employee("Alice", "Sales"),  
    new Employee("Bob", "Marketing"),  
    new Employee("Charlie", "Sales"),  
    new Employee("Dave", "Marketing"),  
    new Employee("Eve", "HR")  
);  
Map<String, List<Employee>> groups = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment));

In this example, we are using a Lambda expression to group the list of employees by their department. The groupingBy() method uses this Lambda expression to create a map that groups the employees by their department. The key of each entry in the map is a string value representing the department of the employees, and the value of each entry is a list of employees in that department.

在本例中,我们使用 Lambda 表达式按部门对员工列表进行分组。groupingBy()方法使用此 Lambda 表达式创建了一个按部门对员工进行分组的映射。映射中每个条目的键是代表员工部门的字符串值,每个条目的值是该部门的员工列表。


【Java】Effective Lambda Expressions in Java(二)https://developer.aliyun.com/article/1395332

相关文章
|
18小时前
|
并行计算 Java API
Java中的函数式编程实战与Lambda表达式应用
Java中的函数式编程实战与Lambda表达式应用
|
1天前
|
Java API 开发者
探索Java中的Lambda表达式
【7月更文挑战第3天】在Java 8的更新中,Lambda表达式无疑是最引人注目的特性之一。它不仅简化了代码编写,还提高了代码的可读性。本文将深入探讨Lambda表达式的概念、语法和实际应用,帮助读者更好地理解和使用这一强大的功能。
9 2
|
1天前
|
Java API
Java 8 Lambda表达式详解
Java 8 Lambda表达式详解
|
1天前
|
算法 Java 编译器
Java基础之lambda表达式(JDK1.8新特性)
Java基础之lambda表达式(JDK1.8新特性)
12 1
|
1天前
|
并行计算 Java 开发者
解析Java中的Lambda表达式用法
解析Java中的Lambda表达式用法
|
2天前
|
存储 Java API
Lambda表达式在Java中的应用详解
Lambda表达式在Java中的应用详解
|
2天前
|
存储 Java API
Lambda表达式在Java中的应用详解
Lambda表达式在Java中的应用详解
|
2月前
|
Java API
Java 8新特性之Lambda表达式与Stream API
【5月更文挑战第17天】本文将介绍Java 8中的两个重要特性:Lambda表达式和Stream API。Lambda表达式是一种新的编程语法,它允许我们将函数作为参数传递给其他方法,从而使代码更加简洁。Stream API是一种用于处理集合的新工具,它提供了一种高效且易于使用的方式来处理数据。通过结合使用这两个特性,我们可以编写出更加简洁、高效的Java代码。
35 0
|
16天前
|
Java 大数据 API
Java中的Lambda表达式和Stream API的高效使用
【6月更文挑战第18天】在Java 8中引入的Lambda表达式和Stream API为集合操作带来了革命性的改进,提供了一种更加简洁、声明式的编程方式。本文将深入探讨如何利用这些特性来提升代码的可读性和开发效率,同时避免常见的性能陷阱。
|
6天前
|
Java API 数据处理
Java中的lambda表达式与Stream API:高效的函数式编程
Java中的lambda表达式与Stream API:高效的函数式编程