In this post, I describe how to do for loop on an Java ArrayList. Array, and HashMap.
Java Array for loop
In the following example, we create an int array, then loop it to add numbers from 1 to 100. Then we loop it again to calculate the sum of the numbers in the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Create an array with room for 100 integers int[] nums = new int[100]; // Fill it with numbers using a for-loop for (int i = 0; i < nums.length; i++) nums[i] = i + 1; // +1 since we want 1-100 and not 0-99 // Compute sum int sum = 0; for (int n : nums) sum += n; // Print the result (5050) System.out.println(sum); |
Java List for loop
We provide four ways to show how to loop a java List.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.Arrays; import java.util.Iterator; import java.util.List; public class JavaLoopExample { public static void main(String[] argv) { String sArray[] = new String[] { "Value 1", "Value 2", "Value 3" }; // convert array to list List<String> list = Arrays.asList(sArray); // iterator loop System.out.println("iterator.hasNext()"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // for loop System.out.println("for loop"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } // for loop advance System.out.println("for loop advance"); for (String temp : list) { System.out.println(temp); } // while loop; System.out.println("while advance"); int j = 0; while (j < list.size()) { System.out.println(list.get(j)); j++; } } } |
iterator.hasNext()
Value 1
Value 2
Value 3
for loop
Value 1
Value 2
Value 3
for loop advance
Value 1
Value 2
Value 3
while advance
Value 1
Value 2
Value 3
Java HashMap for loop
If you’re only interested in the keys,
[Read More...]