Navigation
Recherche
|
How to use method references in Java
jeudi 22 mai 2025, 11:00 , par InfoWorld
Method references in Java are part of the broader set of features introduced and enhanced in Java 8 and beyond. They are a concise way to refer to methods of classes or objects. Method references are especially useful in the context of lambda expressions, where they are used to write cleaner, more readable code. This article is a deep dive into understanding and using method references in your Java programs.
What are method references? Method references are a shorthand way to write lambda expressions that call a single method. Rather than implementing a method in a functional interface, a method reference simply points to an existing method. Method references are most useful for replacing lambda expressions that do nothing but call an existing method. Method references are best used to simplify or enhance the clarity of your code. There are a few cases where they are particularly useful: Simple method delegation: Use method references for straightforward delegations that don’t require modifying or processing arguments. For example, list.forEach(System.out::println) is clearer than a lambda expression like list.forEach(item -> System.out.println(item)). Reusable logic: If the same logic or method is used repeatedly across your code, encapsulating it in a method and then referencing it can reduce duplication. An example is using String::trim on multiple streams or collections. Enhancing readability: In cases where the method name clearly describes the action being performed, method references can make your code more readable. For example, the purpose of map(String::toLowerCase) is immediately clear. The structure of a method reference The following is a classic example of a method reference: ClassName::staticMethod The code instructs the program to “use the static method from this class” instead of writing a lambda. Method references vs. lambda expressions Now let’s compare two examples. The code below uses a lambda expression to convert Strings to Integers: strings.stream().map(s -> Integer.parseInt(s)); Here’s the same operation using a method reference: strings.stream().map(Integer::parseInt); Both examples do the same thing: converting Strings to Integers. However, the method reference is shorter, which makes it easier to read and understand. You might also notice that the Integer.parseInt method contract fits with the map method, which is a Function that takes and returns a value: Stream map(Function
https://www.infoworld.com/article/3956452/how-to-use-method-references-in-java.html
Voir aussi |
56 sources (32 en français)
Date Actuelle
ven. 23 mai - 00:38 CEST
|