Skip to content

Commit 4e39bfb

Browse files
shouvikbhattacharyapivovarit
authored andcommitted
Bael-1305: A Guide to Java Loops (eugenp#3181)
* BAEL-1305: A Simple Guide to Java Loops. * BAEL-1305: Updated article to add few more examples.
1 parent aadde5b commit 4e39bfb

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

‎core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,38 @@
11
package com.baeldung.loops;
22

3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
import java.util.HashSet;
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.Map.Entry;
9+
import java.util.Set;
10+
311
import org.junit.Assert;
12+
import org.junit.BeforeClass;
413
import org.junit.Test;
514

615
public class WhenUsingLoops {
716

817
private LoopsInJava loops = new LoopsInJava();
18+
private static List<String> list = new ArrayList<>();
19+
private static Set<String> set = new HashSet<>();
20+
private static Map<String, Integer> map = new HashMap<>();
21+
22+
@BeforeClass
23+
public static void setUp() {
24+
list.add("One");
25+
list.add("Two");
26+
list.add("Three");
27+
28+
set.add("Four");
29+
set.add("Five");
30+
set.add("Six");
31+
32+
map.put("One", 1);
33+
map.put("Two", 2);
34+
map.put("Three", 3);
35+
}
936

1037
@Test
1138
public void shouldRunForLoop() {
@@ -34,4 +61,47 @@ public void shouldRunDoWhileLoop() {
3461
int[] actual = loops.do_while_loop();
3562
Assert.assertArrayEquals(expected, actual);
3663
}
64+
65+
@Test
66+
public void whenUsingSimpleFor_shouldIterateList() {
67+
for (int i = 0; i < list.size(); i++) {
68+
System.out.println(list.get(i));
69+
}
70+
}
71+
72+
@Test
73+
public void whenUsingEnhancedFor_shouldIterateList() {
74+
for (String item : list) {
75+
System.out.println(item);
76+
}
77+
}
78+
79+
@Test
80+
public void whenUsingEnhancedFor_shouldIterateSet() {
81+
for (String item : set) {
82+
System.out.println(item);
83+
}
84+
}
85+
86+
@Test
87+
public void whenUsingEnhancedFor_shouldIterateMap() {
88+
for (Entry<String, Integer> entry : map.entrySet()) {
89+
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
90+
}
91+
}
92+
93+
@Test
94+
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
95+
aa: for (int i = 1; i <= 3; i++) {
96+
if (i == 1)
97+
continue;
98+
bb: for (int j = 1; j <= 3; j++) {
99+
if (i == 2 && j == 2) {
100+
break aa;
101+
}
102+
System.out.println(i + " " + j);
103+
}
104+
}
105+
}
106+
37107
}

0 commit comments

Comments
 (0)