• 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.

  1. package com.instanceofjava.java8;

  2. import java.util.HashMap;
  3. import java.util.Map;

  4. public class ForEachLoop {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview questions
  8. * Description: java 8 for each loop
  9. *
  10. */
  11. public static void main(String[] args) {
  12. Map<String, Integer> stumarks = new HashMap<>();
  13. stumarks.put("Sai", 65);
  14. stumarks.put("Vamshi", 65);
  15. stumarks.put("Mahendar", 76);
  16. stumarks.put("Muni", 87);
  17. stumarks.put("Manohar", 90);

  18. for (Map.Entry<String, Integer> entry : stumarks.entrySet()) {
  19. System.out.println(entry.getKey() + " marks : " + entry.getValue());
  20. }

  21. }

  22. }

Output:

  1. Muni marks : 87
  2. Vamshi marks : 65
  3. Mahendar marks : 76
  4. Sai marks : 65
  5. 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));

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu