Java 8 lambda foreach List

You must have heard about Lambda Expression introduced in Java 8. Soon we will cover detail topics on it. But now in this article i will show how to use Lambda expression to iterate Collection List. If you want to iterate over Map you can check Java 8 lambda foreach Map article.

Listing 1 : Iterate using for loop

class java_forLoop_list {
	public static void main(String[] args) {
		List<String> jbtObjs = new ArrayList<>();
		jbtObjs.add("Java");
		jbtObjs.add("Beginners");
		jbtObjs.add("Tutorial");

		for(int i=0; i<jbtObjs.size();i++){
			System.out.println(jbtObjs.get(i));;
		}
		Iterator i = jbtObjs.iterator();
		while (i.hasNext())
		  {
		    String name = (String) i.next();
		    System.out.println(name);
		  }
	}
}

Listing 2 : Iterate using enhanced for Loop (Java 5)

class java_5_enhancedForLoop_list {
	public static void main(String[] args) {
		List<String> jbtObjs = new ArrayList<>();
		jbtObjs.add("Java");
		jbtObjs.add("Beginners");
		jbtObjs.add("Tutorial");

		for (String jbtObj : jbtObjs) {
			System.out.println(jbtObj);
		}
	}
}

Listing 3 : Java 8 Lambda forEach

public class java_8_forEach_list {
	public static void main(String[] args) {
		List<String> jbtObjs = new ArrayList<>();
		jbtObjs.add("Java");
		jbtObjs.add("Beginners");
		jbtObjs.add("Tutorial");

		jbtObjs.forEach(name -> System.out.println(name));
	}
}

 

By | 2016-02-12T12:05:10+00:00 February 12th, 2016|Core Java|0 Comments

About the Author:

Leave A Comment