Loops are used to iterate items on a list or to traverse a certain part of the program several times as long as a condition is satisfied.
What are the different ways to perform loops in Java List?
In this post, we will briefly cover various ways to run loops in Java with an example.
- FOR
- Enhanced FOR
- WHILE
- DO WHILE
- FOR EACH
FOR
This is the most traditional loop in Java.
In this loop, we initialize a variable, evaluate a condition and change the variable value in each iteration.
public static void forLoop() {
System.out.println("forLoop");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
for (int i = 0; i < values.size(); i++) {
System.out.println(values.get(i));
}
}
Enhanced FOR
This is more readable and It is simpler than the previous sentences.
The ‘enhanced for loop’ run sequentially. The counter is always increased internally by one.
public static void enhancedLoop() {
System.out.println("enhancedLoop");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
for (Integer e : values) {
System.out.println(e);
}
}
WHILE
WHILE iterating the list as long the condition is satisfied.
Here we have the expression ‘while’ that evaluates a condition. If this condition is true, continue with the cycle but if it is false it exits the loop.
public static void whileLoop() {
System.out.println("whileLoop");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
int i = 0;
while (i < values.size()) {
System.out.println(values.get(i));
i++;
}
}
DO WHILE
It is similar to the previous one but the condition is at the end here.
So, It will always go through at least one iteration.
Notice that ‘while’ is at the end of the sentence.
public static void doWhileLoop() {
System.out.println("doWhileLoop");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
int i = 0;
do {
System.out.println(values.get(i));
i++;
} while (i < values.size());
}
The difference between a ‘WHILE’ and a ‘DO WHILE’ is when the boolean condition occurs. In ‘WHILE’ the boolean condition is the first thing that happens. In contrast, ‘DO WHILE’ occurs at the end.
FOR EACH
‘For Each’ loop was introduced in Java 8.
We use forEach to iterate a collection and do some action on every element of this collection.
The action we do with each element is executed by a Consumer. This consumer receives the current element in order to work with it.
public static void forEachFunctionalLoop() {
System.out.println("forEachFunctionalLoop");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
// using anonymous class
values.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer x) {
System.out.println(x);
}
});
// using lambda
values.forEach(x -> System.out.println(x));
// using method reference :)
values.forEach(System.out::println);
}
Here are three extra useful ways to iterate lists using ‘iterator’ and ‘stream’.
Note that we are really using the loops we saw above but in combination with the ‘iterator’ and ‘stream’ API.
ITERATOR
This loop format uses an Iterator interface supplied by the collection, in this case, supplied by the list. This interface provides a method hasNext() that we can use to evaluate the condition.
If you look we use ‘FOR’ and ‘WHILE’.
We get an iterator that is moving one by one. Here the condition will be that there is the next element so we can use this condition to comply with the loop’s condition.
public static void iteratorLoop() {
System.out.println("iteratorLoop");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
for (Iterator<Integer> iter = values.iterator(); iter.hasNext(); ) {
Integer element = iter.next();
System.out.println(element);
}
Iterator<Integer> iter = values.iterator();
while (iter.hasNext()) {
Integer next = iter.next();
System.out.println(next);
}
}
LIST ITERATOR
It is very similar to the ‘iterator loop’. The difference here is that you can iterate in both directions, forward o backward.
public static void listIteratorLoop() {
System.out.println("listIteratorLoop");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
ListIterator<Integer> valuesListIterator = values.listIterator();
// forward
while (valuesListIterator.hasNext()) {
Integer next = valuesListIterator.next();
System.out.println(next);
}
// backward / reverse
while (valuesListIterator.hasPrevious()) {
System.out.println(valuesListIterator.previous());
}
}
STREAM + FOR EACH
Here we can use a stream to apply some method of the stream API and after that, we call forEach.
public static void forEachStream() {
System.out.println("forEachStream");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
// the main idea for streams is to apply some function to the data
// for example 'filter'
values.stream().filter(e -> e > 0).forEach(System.out::println);
}
Conclusion
In this post, we saw how to perform loops in Java in order to iterate a list with elements. We understood the use of ‘for, enhanced for, while, do while, for each’ Java sentence.
This code is in GitHub