- Java 8 introduces for each loop.
- before that lest see an example of how normal java for each loop.
#1: Java Example program which explain use of for each loop.
- package com.instanceofjava.java8;
- import java.util.HashMap;
- import java.util.Map;
- public class ForEachLoop {
- /**
- * @author www.Instanceofjava.com
- * @category interview questions
- *
- * Description: java 8 for each loop
- *
- */
- public static void main(String[] args) {
- Map<String, Integer> stumarks = new HashMap<>();
- stumarks.put("Sai", 65);
- stumarks.put("Vamshi", 65);
- stumarks.put("Mahendar", 76);
- stumarks.put("Muni", 87);
- stumarks.put("Manohar", 90);
- for (Map.Entry<String, Integer> entry : stumarks.entrySet()) {
- System.out.println(entry.getKey() + " marks : " + entry.getValue());
- }
- }
- }
Output:
- Muni marks : 87
- Vamshi marks : 65
- Mahendar marks : 76
- Sai marks : 65
- Manohar marks : 90
#2: Java Example program which explains the use of for each loop in java 8
- In the above program we used for each loop to get key value pairs of map.
- Same thing will be done in java 8 by using stumarks.forEach((k,v)->System.out.println( k + " marks : " + v));
No comments