Using for-each
command to iterate arrays or a list can simplified our code. Below is an example how to do it in Java. The first loop is for iterating array and the second for iterating a list containing a some names.
package org.kodejava.lang;
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};
for (Integer i : numbers) {
System.out.println("Number: " + i);
}
List<String> names = new ArrayList<>();
names.add("Musk");
names.add("Nakamoto");
names.add("Einstein");
for (String name : names) {
System.out.println("Name: " + name);
}
}
}
The result of the code snippet:
Number: 10
Number: 100
Number: 1000
Number: 10000
Number: 100000
Number: 1000000
Name: Musk
Name: Nakamoto
Name: Einstein
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024