CodesJava

Easy learning with example program codes

Java 8 forEach example


Java 8 introduced forEach method to iterate over the collections and Streams in Java. It is defined in Iterable and Stream interface. It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach loop to iterate elements.

Java 8 forEach example

package com.codesjava;
 
import java.util.HashMap;
import java.util.Map;
 
public class Test{  
    public static void main(String[] args) {  
    	Map<Integer, String> hashMap = new HashMap<Integer, String>();
    	hashMap.put(1, "Jai");
    	hashMap.put(2, "Mahesh"); 
    	hashMap.put(3, "Vishal");  
    	hashMap.put(4, "Vivek");   
    	hashMap.put(5, "Hemant");   
    	hashMap.put(6, "Naren");
        //forEach to iterate and display each key and value pair    
    	hashMap.forEach((key,value)->System.out.println(key+" - "+value));
    }  
}

Output

1 - Jai
2 - Mahesh
3 - Vishal
4 - Vivek
5 - Hemant
6 - Naren


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki