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.
This commit is contained in:
Shouvik Bhattacharya 2017-12-03 02:24:36 +05:30 committed by Grzegorz Piwowarek
parent aadde5b526
commit 4e39bfb945
1 changed files with 70 additions and 0 deletions

View File

@ -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<String> list = new ArrayList<>();
private static Set<String> set = new HashSet<>();
private static Map<String, Integer> 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<String, Integer> 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);
}
}
}
}