DEV Community

FUNDAMENTOS JAVA
FUNDAMENTOS JAVA

Posted on

1 1 1 1 1

6.5 Referenciando métodos que recebem argumen tos

Referenciando métodos que aceitam parâmetros:

Podemos usar method references para métodos que recebem argumentos, como println da classe PrintStream.
Exemplo:

usuarios.forEach(System.out::println);

Enter fullscreen mode Exit fullscreen mode

O compilador entende que System.out::println é equivalente a um lambda:

u -> System.out.println(u);

Enter fullscreen mode Exit fullscreen mode

Durante a iteração com forEach, cada elemento da lista é passado automaticamente como argumento para println.
Equivalência com código Java 7:

O método reference é equivalente ao laço tradicional:

for (Usuario u : usuarios) {
    System.out.println(u);
}

Enter fullscreen mode Exit fullscreen mode

Importância do toString:

Para exibir corretamente os usuários, o método toString deve ser sobrescrito na classe Usuario:

public String toString() {
    return "Usuario " + nome;
}

Enter fullscreen mode Exit fullscreen mode

Exemplo completo em Java:

public class Capitulo6 {
    public static void main(String... args) {
        Usuario user1 = new Usuario("Paulo Silveira", 150);
        Usuario user2 = new Usuario("Rodrigo Turini", 120);
        Usuario user3 = new Usuario("Guilherme Silveira", 190);

        List<Usuario> usuarios = Arrays.asList(user1, user2, user3);

        usuarios.forEach(System.out::println);
    }
}

Enter fullscreen mode Exit fullscreen mode

Esse código cria uma lista de usuários e imprime cada um usando System.out::println.

Conclusão:
Quando usamos System.out::println, o compilador entende que cada item da lista será passado como argumento ao método println.
Method references tornam o código mais conciso e legível.
O toString da classe Usuario deve ser sobrescrito para que a saída seja mais informativa.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay