Lambda List Iteration Java

Lambda List Iteration Java

Here I will show you old way to iterating list and by using Lambda which got introduced in Java 8. Please have example code below:

  • LambdaListIteration.java:
package com.javahonk;

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

public class LambdaListIteration {

	public static void main(String[] args) {
		
		List<String> list = new ArrayList<String>();
		
		list.add("Test1");
		list.add("Test2");
		
		//Old pattern		
		for (String string : list) {
			System.out.println(string);
		}
		
		//New JDK 8 Lambda code migration		
		list.forEach(n->System.out.println(n));
		
		//OR
		list.forEach(n -> {
			String value = n;
			System.out.println(value);
		});
		
		//OR use double colon to call method
		list.forEach(System.out::println);
		
		//OR use double colon to call method		
		list.forEach(LambdaListIteration::printValue);
	}
	
	private static void printValue(String value){
		System.out.println(value);
	}

}
  • Output:

Lambda List Iteration Java

  • For more information please visit Oracle tutorial here

Leave a Reply

Your email address will not be published. Required fields are marked *