All the Collection Interfaces in Java (List, Set, Map etc) will be extending the Iterable interface as the super interface. In Java 8 a new method has been introduced for Iterating over collections in Java.
void forEach(Consumer<? super T> action)
In this Java 8, ForEach Example article lets see how to iterate through a List and Map with the new forEach Loop in Java 8.
Iterate through ArrayList in Java using forEach Loop
Using Java 7 or less
package com.javainterviewpoint; import java.util.ArrayList; public class Iterate_ArrayList { public static void main(String[] args) { //Create a new ArrayList ArrayList countryList = new ArrayList(); //Add elements to the countryList countryList.add("India"); countryList.add("England"); countryList.add("Australia"); countryList.add("Japan"); //iterate through list in java for (String country : countryList) { System.out.println(country); } } }
Using Java 8 ForEach Example ArrayList
package com.javainterviewpoint; import java.util.ArrayList; public class Iterate_ArrayList { public static void main(String[] args) { //Create a new ArrayList ArrayList countryList = new ArrayList(); //Add elements to the countryList countryList.add("India"); countryList.add("England"); countryList.add("Australia"); countryList.add("Japan"); //iterate through list in Java 8 using forEach Lambda Expression countryList.forEach(country->System.out.println(country)); //iterate through list in Java 8 using forEach method reference countryList.forEach(System.out::println); } }
Output:
Iterating a Map in Java using forEach Loop
Using Java 7 or less
package com.javainterviewpoint; import java.util.HashMap; import java.util.Map; public class Iterate_Map { public static void main(String[] args) { // Create a new HashMap HashMap<String, String> countryMap = new HashMap<String, String>(); // Add elements to the countryMap countryMap.put("1", "India"); countryMap.put("2", "England"); countryMap.put("3", "Australia"); countryMap.put("4", "Japan"); //iterate through map in java for (Map.Entry<String, String> entry : countryMap.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } } }
Using Java 8 forEach Map
package com.javainterviewpoint; import java.util.HashMap; import java.util.Map; public class Iterate_Map { public static void main(String[] args) { // Create a new HashMap HashMap<String, String> countryMap = new HashMap<String, String>(); // Add elements to the countryMap countryMap.put("1", "India"); countryMap.put("2", "England"); countryMap.put("3", "Australia"); countryMap.put("4", "Japan"); //iterate through map in Java 8 using forEach Lambda Expression countryMap.forEach((key,value)->System.out.println("Key : "+ key+" Value: "+value)); } }
Output :
Key : 1 Value: India
Key : 2 Value: England
Key : 3 Value: Australia
Key : 4 Value: Japan
Leave a Reply