Java for Loop

Tags: , , , ,

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. 

Java List for loop

We provide four ways to show how to loop a java List. 

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, you can iterate through the keySet() of the map:

If you only need the values, use values():

Finally, if you want both the key and value, use entrySet():