• 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));

java+8+for+each+loop

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
How to remove html tags from string java
»
Previous
Java 8 java.util.function.Function with example program

No comments

Leave a Reply

Select Menu