Introduction
Loops allow you to iterate over collections, repeat actions, and control the flow of our programs. In this post, we'll explore the different types of loops in Java and when to use each one.
For Loop
The for loop is available in most programming languages. It's ideal for situations where you know the exact number of iterations needed.
|
|
For-Each
The for-each loop, simplifies iterating over collections and arrays.
|
|
Iterating over Maps
In addition to lists and arrays, the for-each loop can also be used to iterate over the entries of a Map. This is particularly useful when you need to access both the keys and values of the map within the loop.
|
|
In this example, we use the entrySet()
method to get a set of all the map's entries, which we can then iterate over using the
enhanced for loop. Each entry contains a key-value pair that we can access using the getKey()
and getValue()
methods.
While Loop
While loops execute their body as long as a given condition is true. They're useful when the number of iterations is unknown.
|
|
Do-While Loop
Do-while loops are similar to while loops, but they guarantee that the body will execute at least once, even if the condition is initially false.
|
|