Iterating over Java Enum

  • Last updated:February 5, 2018
  • / Java

Java Enum is a special data type provides a feature to define set of predefined constants.In this post, we will discuss different methods for Iterating over Java Enum.

 

 

1. Iterating over Java Enum Values

Before we start iterating over Java Enum values, let’s create a simple enum class for our post.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEBNESDAY, THRUSDAY, FRIDAY, SATURDAY
}

Note that enum does not have any method like forEach() or iterator() to support iteration.

 

1.1 Iterate using for loop

Enum provides values() method which returns predefined value. One of the simplest options for Iterating over Java Enum is to use the for loop.

 for(Day day : Day.values()){
         System.out.println("Day is :"+ day.name());
  }

Note that, values() is an implicit method provided by the compiler.

 

1.2 Iterate using Stream

With the Java 8 introduction to stream, we can use java.util.stream.This is recommended way if we are planning to perform parallel operations.

We can use Stream.of() or Arrays.stream() method for the iteration.

Stream.of(Day.values()).forEach(System.out::println);
Arrays.stream(Day.values()).forEach(System.out::println);

We can use Java 8 steam and lambda to iterate over enum and filter results based on the requirement. 

public enum LanguageEnum {
    
   JAVA("1"), C("2") ,SCALA("3"),PYTHON("4");
   String selectedLanguage;
   LanguageEnum(String selectedLanguage) {
        this.selectedLanguage = selectedLanguage;
    }
}

public class LanguageExample {
    public static void main(String[] args) {
       Arrays.stream(LanguageEnum.values()).filter(l -> l.selectedLanguage.equals("1")).forEach(System.out::println);
    }
}

Output

JAVA

 

1.3 Iterate using forEach()

For using forEach() loop, We need to convert enum to a java list or set.

  • To convert Enum in to set, use EnumSet.it is a specialized Set implementation for use with enum types.
  • For converting enum to list, we can use Arrays.asList() method.
 public static void main(String[] args) {
    EnumSet.allOf(Day.class).forEach(day-> System.out.println("day is "+day));
 }

  //List
  public static void main(String[] args) {
     Arrays.asList(Day.values()).forEach(day -> System.out.println("day is " +day));
  }

 

Summary

In this post, we covered different options for Iterating over Java Enum.We explored Java 8 stream API for the iteration along with the traditional for loop.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of