JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java 8 - forEach method example with List


forEach is a new method introduced in Java 8 to iterate over collections. Here is an example on forEach method to iterate over List.

package com.java2novice.java8;

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

public class ForEachListEx {

	public static void main(String a[]) {

		List<String> countryList = new ArrayList<>();
		countryList.add("India");
		countryList.add("USA");
		countryList.add("Japan");
		countryList.add("Canada");

		// iterate through List normal way
		ForEachListEx.iterateList(countryList);

		// iterate through List using forEach method
		ForEachListEx.iterateListUsingForEach(countryList);
	}

	public static void iterateList(List<String> countryList) {

		System.out.println("<-----Iterating in normal way----->");
		for(String country:countryList) {
			System.out.println(country);
		}
	}

	public static void iterateListUsingForEach(List<String> countryList) {

		System.out.println("\n<---Iterating using forEach method--->");
		countryList.forEach(country->System.out.println(country));

		countryList.forEach(country->{
			// you can implement some business logic here..
		});
	}
}

Output:
<-----Iterating in normal way----->
India
USA
Japan
Canada

<---Iterating using forEach method--->
India
USA
Japan
Canada
<< Previous Program 

Java 8 forEach method examples

  1. Java 8 forEach example with Map
  2. Java 8 forEach example with List
Knowledge Centre
What is fail-fast in java?
A fail-fast system is nothing but immediately report any failure that is likely to lead to failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators. Incase, you have called iterator on a collection object, and another thread tries to modify the collection object, then concurrent modification exception will be thrown. This is called fail-fast.
Famous Quotations
The greatest obstacle to discovery is not ignorance; it is the illusion of knowledge.
-- Daniel J. Boorstin

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2018 by Nataraja Gootooru. All Rights Reserved.