Monday, March 4, 2013

How to Iterate over Java Enum using values and for loop

In this Java programming tutorial, we will learn how to iterate over enum in Java. Since Enums are collection of finite number of objects, often we need to iterate over them. Enums are also final in Java and has private constructor, which means you can not create enum instances once declared. Iteration over Enum is extremely simple, provided you know about implicit values() method, which is a static method, provided by java.lang.Enum. Since every enum in Java extends java.lang.Enum, they all get this implicit values() method. Actually there are couple of them, e.g. valueOf(), name(), ordinal() etc.In last couple of Java tutorials on enum we have seen How to convert Enum to String in Java, Enum valueOf Example and Enum Constructor Example. This tutorial focuses on iteration over Enum in Java.


How to iterate over Enum in Java

In this Java program, we have created an enum called Language, which represent programming language and there rank. Our task is to iterate through this enum and print name, and rank of each enum instance. Just remember that, all enum in Java provides values() method, which returns an array of enum, containing all instances. Here is full code example of Iterating over enum :

/**
 * Java program to iterate over enum using for loop and values method.
 * values() method of enum returns all enum instances as array for iteration.
 *
 * @author java67
 */
public class EnumHowTo {

    public enum Language{
        JAVA(1), PYTHON(2), PERL(3), SCALA(4);
   
        private int rank;
       
        private Language(int rank){
            this.rank = rank;
        }
       
        public int getRank(){
            return rank;
        }
   
    };
   
    public static void main(String args[]) {

        System.out.println("Java Enum Iterate Example using for loop");
       
        for(Language pl : Language.values()){
            System.out.println( pl.name() + " : " + pl.rank);
        }
   
    } 
   
}

Output:
Java Enum Iterate Example using for loop
JAVA : 1
PYTHON : 2
PERL : 3
SCALA : 4
That's all on How to iterate over enum in Java. As I said earlier and you can see from this code example, its simple. Don't forget values() method, which return array of enum instances. To learn more about Enum in Java and there usages, see following tutorials :

1 comment:

  1. why you are maintaing 2 blogs...javarevisited and java67? if u can consolidate everything in one it will be useful for the readers

    ReplyDelete

Java67 Headline Animator