Tuesday, 3 May 2016

How to Iterate over a ArrayList using Lambda Expression in Java 8

Iterate over a ArrayList using Lambda Expression

Using the Lambda Expression feature in Java 8 we can easily iterate over a list of items easily.
This can be done in this way.

Example 1. Simply Iterate over a List and Print the Items.

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

public class IterateList {

 public static void main(String[] args) {
  List items = new ArrayList<>();
  items.add("Hello");
  items.add("Java");
  items.add("Welcome");
  items.add("to");
  items.add("Codermagnet");

  //iterate list and print the items
  items.forEach(System.out::println);

 }
}


Output:
Hello
Java
Welcome
to
Codermagnet


Example 2. Iterate over a List and do operations on the list items.

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

public class IterateList {

 public static void main(String[] args) {
  List items = new ArrayList<>();
  items.add("Hello");
  items.add("Java");
  items.add("Welcome");
  items.add("to");
  items.add("Codermagnet");
  
  //Iterate over a list and call a function
  //items.forEach(item -> System.out.println(item));
  //OR like this 
  items.forEach(item -> printData(item));

 }

 public static void printData(String item) {
  System.out.println("Hello " + item);
  //Your Business Logic here
 }
}


Output:
Hello Hello
Hello Java
Hello Welcome
Hello to
Hello Codermagnet


No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.