Java - How to loop an enum
In this section, we will write a Java program to loop an enum.
Call the .values() method of the enum class to return an array, and loop it with the for loop:
for(Country country:Country.values())
{
System.out.println(country);
}
For Java 8, convert an enum into a stream and loop it:
Stream.of(Country.values()).forEach(System.out::println);
1. For Loop Enum
1.1 An enum
to contain a list of the countries:
Country.java
public enum Country {
USA,
India,
China,
Russai,
Brazil,
France;
}
1.2 To loop over the above enum
class, just call .values()
and do a normal for loop
Main.java
public class Main {
public static void main(String[] args) {
for(Country country:Country.values())
{
System.out.println(country);
}
}
}
Console Output:
USA
India
China
Russai
Brazil
France
2. Java 8 Stream APIs
2.1 Convert an enum
into a stream and loop it.
Main.java
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream.of(Country.values()).forEach(System.out::println);
}
}
Console Output:
USA
India
China
Russai
Brazil
France
More topics,