From 4e39bfb945ddd83f208a193c527a32787888b036 Mon Sep 17 00:00:00 2001 From: Shouvik Bhattacharya <33756821+shouvikbhattacharya@users.noreply.github.com> Date: Sun, 3 Dec 2017 02:24:36 +0530 Subject: [PATCH] Bael-1305: A Guide to Java Loops (#3181) * BAEL-1305: A Simple Guide to Java Loops. * BAEL-1305: Updated article to add few more examples. --- .../com/baeldung/loops/WhenUsingLoops.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java index 9590eabfef..f82f9ddaa7 100644 --- a/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java +++ b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java @@ -1,11 +1,38 @@ package com.baeldung.loops; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; public class WhenUsingLoops { private LoopsInJava loops = new LoopsInJava(); + private static List list = new ArrayList<>(); + private static Set set = new HashSet<>(); + private static Map map = new HashMap<>(); + + @BeforeClass + public static void setUp() { + list.add("One"); + list.add("Two"); + list.add("Three"); + + set.add("Four"); + set.add("Five"); + set.add("Six"); + + map.put("One", 1); + map.put("Two", 2); + map.put("Three", 3); + } @Test public void shouldRunForLoop() { @@ -34,4 +61,47 @@ public class WhenUsingLoops { int[] actual = loops.do_while_loop(); Assert.assertArrayEquals(expected, actual); } + + @Test + public void whenUsingSimpleFor_shouldIterateList() { + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void whenUsingEnhancedFor_shouldIterateList() { + for (String item : list) { + System.out.println(item); + } + } + + @Test + public void whenUsingEnhancedFor_shouldIterateSet() { + for (String item : set) { + System.out.println(item); + } + } + + @Test + public void whenUsingEnhancedFor_shouldIterateMap() { + for (Entry entry : map.entrySet()) { + System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue()); + } + } + + @Test + public void whenUsingSimpleFor_shouldRunLabelledLoop() { + aa: for (int i = 1; i <= 3; i++) { + if (i == 1) + continue; + bb: for (int j = 1; j <= 3; j++) { + if (i == 2 && j == 2) { + break aa; + } + System.out.println(i + " " + j); + } + } + } + }