Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Method Reference | enum & Stream API
Java Data Structures
course content

Contenido del Curso

Java Data Structures

Java Data Structures

1. Basic Data Structures
2. Additional Data Structures
3. Map
4. enum & Stream API

bookMethod Reference

Before diving into practice with the Stream API, we should explore some shortcuts for lambda expressions. Programmers refer to these "shortcuts" as syntactic sugar.

In this chapter, we will discuss method references and how to use them as substitutes for lambda expressions.

Method References

Let's take a look at a simple example of a lambda expression and try to replace it with a method reference:

java

main

copy
1234567891011
package com.example; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> example = Arrays.asList("c", "o", "d", "e", "f", "i", "n", "i", "t", "y"); example.stream().map(e -> e.toUpperCase()).forEach(e -> System.out.print(e)); } }

Using two lambda expressions doesn't look very elegant, especially when we can shorten them to method references from the classes where they are declared.

The syntax will look like this:

java

example

copy
1
(Class::Method)

Let's improve the above code using method references:

java

main

copy
1234567891011
package com.example; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> example = Arrays.asList("c", "o", "d", "e", "f", "i", "n", "i", "t", "y"); example.stream().map(String::toUpperCase).forEach(System.out::print); } }

The toUpperCase method is part of the String class, so we use the construction String::toUpperCase. Note that when using a method reference, the operation will be applied to each element, so there is no need to use a lambda expression for this. We also replaced the print to the screen with System.out::print, which is also a method reference. The program will apply the System.out.print() method to each element.

By the way, IntelliJ IDEA itself constantly suggests replacing lambda expressions with method references if such an operation is possible, so you don't have to memorize the syntax every time:

In this way, IntelliJ IDEA itself will suggest improving your code using method references.

Summary

In summary, method references do not add any programmatic burden. They do not optimize the process but also do not complicate it. This construction is simply for reducing the written code slightly and improving readability. Whether to use lambda expressions or method references is up to you. For example, I find it clearer to write a lambda expression, and then IntelliJ will automatically replace it with a method reference.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
some-alt