Skip to content

Brilliant Coding Blog

Be Brilliant

Refactoring a For-Loop to a Lambda in Java

Tags:
Posted on: Last modified: Published by: Matthew Jackowski

This is a quick example to show refactoring a ‘for-loop’ over a List of objects by using a Lambda function instead.

We will take a simple List of Message objects and simply output the name of the message. Typically you may want to perform various side affects instead of the outputting the object’s name on a message list like this. Using Java lambdas reduces the amount of code needed to do this!

Message[] messageArray = {new Message(0), new Message(1), new Message(2)};
List messages =  Arrays.asList(messageArray);
        
for (Message message: messages) {
        System.out.println(message);
}

Instead we will replace the for block with a single lambda statement:

Message[] messageArray = {new Message(0), new Message(1), new Message(2)};
List messages =  Arrays.asList(messageArray);
        
messages.forEach((message) -> System.out.println(message));

This is great but we can do better by using the Java 8 method reference instead:

Message[] messageArray = {new Message(0), new Message(1), new Message(2)};
List messages =  Arrays.asList(messageArray);

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

The final version of this code can be found in a Gist here.

Refactoring a For-Loop to a Lambda in Java