How to iterate Enum in Java


This guide walks you through how to iterate Enum in Java/Java 8. .values() method of an enum class return an array and we can loop it:

Using Java 8, convert an enum into a stream and iterate it.

Stream.of(CountryEnum.values()).forEach(System.out::println);

Using Java <=7, loop it through Enhanced For Loop.

for (CountryEnum country : CountryEnum.values()) {

	System.out.println(country);
}

1. Java 8 Stream API

1.1 An enum that contains a list of popular country.

CountryEnum.java
package org.websparrow;

public enum CountryEnum {

	INDIA, USA, THAILAND, UK, GERMANY
}

1.2 Convert an enum into a stream and loop it.

Main.java
package org.websparrow;

import java.util.stream.Stream;

public class Main {

	public static void main(String[] args) {

		Stream.of(CountryEnum.values()).forEach(System.out::println);

	}
}

Output

INDIA
USA
THAILAND
UK
GERMANY

1.3 Match the country INDIA

Stream.of(CountryEnum.values())
.filter(name -> name.toString().equals("INDIA"))
.forEach(System.out::println);

Output

INDIA

1.4 Filter out the country UK

Stream.of(CountryEnum.values())
.filter(name -> !name.toString().equals("UK"))
.forEach(System.out::println);

Output

INDIA
USA
THAILAND
GERMANY

2. Enhanced For Loop

To iterate over the above enum class, call .values() method and do a normal for loop.

Main.java
package org.websparrow;

public class Main {

	public static void main(String[] args) {

		for (CountryEnum country : CountryEnum.values()) {

			System.out.println(country);
		}
	}
}

Output

INDIA
USA
THAILAND
UK
GERMANY

References

  1. Java Enum

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.