Iterating over Java Enum | Java Development Journal

Iterating over Java Enum

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.

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of