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,

Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example