How to print a list or a collection using Lambda Expression in Java 8 - Java @ Desk

Wednesday, October 4, 2017

How to print a list or a collection using Lambda Expression in Java 8

How to print a list or a collection using Lambda Expression in Java 8

In this example, we will learn how to print a list using Lambda expression in Java 8. Traditional methods were using the normal for loop and use the System.out.println method to print the content of a collection.

There are 2 ways to print a list using Lambda expression -
1) Using lambda expression and functional operations
2) Using double colon operator in Java 8

Both these ways reduce the code to a single statement which is more readable and easy to maintain.

Below is the short example to demonstrate both the examples.
package com.lambda;

import java.util.ArrayList;
import java.util.List;

public class ForLoopPrint {

 public static void main(String args[]) {

  List<String> persons = new ArrayList<>();

  persons.add("John");
  persons.add("Adam");
  persons.add("Peter");
  persons.add("James");

  System.out.println("Using Old Loop");
  for (String person : persons) {
   System.out.print(person + "; ");
  }
  System.out.println("\n");

  System.out.println("Using lambda expression and functional operations");
  persons.forEach((person) -> System.out.print(person + "; "));

  System.out.println("\n");
  System.out.println("Using double colon operator in Java 8");
  persons.forEach(System.out::println);
 }
}


Here is the output -
Using Old Loop
John; Adam; Peter; James; 

Using lambda expression and functional operations
John; Adam; Peter; James; 

Using double colon operator in Java 8
John
Adam
Peter
James






No comments:

Post a Comment