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,

Popular posts from this blog

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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

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

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete