DEV Community

Cover image for What are method references in Java?
Wagner Negrão 👨‍🔧
Wagner Negrão 👨‍🔧

Posted on • Updated on

What are method references in Java?

Hi guys, today the post will be short, I’ll write about method references. I know that are simples to understand, but some things were stranger when I first saw them, that is why I’ll write about them.

Methods references are introduced with the Java 8, allowing done references when methods are instanced in lambda expressions, this strategy sought ways to create a non-verbose method.

Let’s go see an example.

List<Person> list = Arrays.asList(new Person("Riot", 112), new Person("Rext", 30));

// Without method reference
list.forEach(e -> System.out.println(e));

// With lambda reference
list.forEach(System.out::println);

// Without method reference
list.stream().map(e -> e.getNumber()).forEach(e -> System.out.println(e));

// With lambda reference
list.stream().map(Person::getNumber).forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode

When using functions lambda often faces moments that need to send the only method, for example, filter(), map() like the example above, but we must remember that when we use methods reference, the parameters are passed directly to the method, don't possible do anything with this parameter.

The :: is a delimiter, that we say we using methods references to code, that way when to run occurs is translated to a functional interface, that is why the code will compile, and this will compile without cost to the application. We must use this form of work, but without forgetting of legibility of code.

Top comments (0)