From c9637e95fd2f43c54f485ea97e297c23fe33fda3 Mon Sep 17 00:00:00 2001 From: vaibhav007jain <72961247+vaibhav007jain@users.noreply.github.com> Date: Sun, 27 Mar 2022 09:03:29 +0530 Subject: [PATCH] BAEL-5463: added code for for-each loop in Java. (#11960) --- .../controlstructures/loops/ForEachLoop.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/controlstructures/loops/ForEachLoop.java diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/controlstructures/loops/ForEachLoop.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/controlstructures/loops/ForEachLoop.java new file mode 100644 index 0000000000..88f49f60db --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/controlstructures/loops/ForEachLoop.java @@ -0,0 +1,57 @@ +package com.baeldung.core.controlstructures.loops; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class ForEachLoop { + + public static void main(String[] args) { + + int[] numbers = { 1, 2, 3, 4, 5 }; + List wordsList = new ArrayList<>(); + wordsList.add("Java"); + wordsList.add("is"); + wordsList.add("great!"); + + Set wordsSet = new HashSet<>(); + wordsSet.addAll(wordsList); + + Map map = new HashMap<>(); + map.put(1, "Java"); + map.put(2, "is"); + map.put(3, "great!"); + + traverseArray(numbers); + traverseList(wordsList); + traverseSet(wordsSet); + traverseMap(map); + } + + private static void traverseMap(Map map) { + for (Map.Entry entry : map.entrySet()) { + System.out.println("number: " + entry.getKey() + " - " + "word: " + entry.getValue()); + } + } + + private static void traverseSet(Set wordsSet) { + for (String word : wordsSet) { + System.out.println(word + " "); + } + } + + private static void traverseList(List wordsList) { + for (String word : wordsList) { + System.out.println(word + " "); + } + } + + private static void traverseArray(int[] numbers) { + for (int number : numbers) { + System.out.println(number + " "); + } + } +}