3

What are method references?

 2 years ago
source link: https://dev.to/wagnernegrao/what-are-method-references-3ng
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
What are method references?

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 modeExit 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK