'java.lang.Iterable'
interface provides forEach method to perform the given action on each element
of the iterable. The default implementation of forEach method looks like below.
As
you see the default implementation, for each method traverse through each entry
of the iterable and perform given action on it.
Example 1: Print country names
from the list using forEach function.
countryNames.forEach((data
-> {
System.out.println(data);
}));
Example 2: Print country names
in upper case from the list using forEach function.
countryNames.forEach((data
-> {
System.out.println(data.toUpperCase());
}));
Find
the below working example.
Test.javapackage com.sample.app; import java.util.ArrayList; import java.util.List; public class Test { private static List<String> countryNames = new ArrayList<>(); private static void loadCountriesMap() { countryNames.add("Belgium"); countryNames.add("Cuba"); countryNames.add("Georgia"); countryNames.add("Mongolia"); countryNames.add("Nepal"); countryNames.add("Poland"); countryNames.add("Sweden"); } static { loadCountriesMap(); } public static void main(String args[]) { /* Print country names */ System.out.println("Country names in raw form"); countryNames.forEach((data -> { System.out.println(data); })); /* Print country names in upper case */ System.out.println("\nCountry names in upper case"); countryNames.forEach((data -> { System.out.println(data.toUpperCase()); })); } }
Output
Country names in raw form Belgium Cuba Georgia Mongolia Nepal Poland Sweden Country names in upper case BELGIUM CUBA GEORGIA MONGOLIA NEPAL POLAND SWEDEN
No comments:
Post a Comment