Enum to Integer and Integer to Enum in Java

Published on November 5, 2015 by

Need to convert an integer to an enum in Java? The bad news is that it is not as easy as it should be, but the good news is that it is still easy!

Consider the enum below.

public enum PageType {
    ABOUT(1),
    CODING(2),
    DATABASES(3);

    private int value;
    private static Map map = new HashMap<>();

    private PageType(int value) {
        this.value = value;
    }

    static {
        for (PageType pageType : PageType.values()) {
            map.put(pageType.value, pageType);
        }
    }

    public static PageType valueOf(int pageType) {
        return (PageType) map.get(pageType);
    }

    public int getValue() {
        return value;
    }
}

With the above enum, one can get the enum from an integer, but also get the integer based on an enum. The trick here is to use a map internally which handles the mapping of an integer (or whichever type you need) to its corresponding enum. This is done in a static method, which iterates through the values within the enum and adds them to the map. There is also a private constructor where we assign the passed value to a variable. This is done automatically upon using an enum due to the parenthesis after each enum name.

Getting Enum from Integer

To get the enum for a given integer, we simply have to call the valueOf method, like below.

PageType pageType = PageType.valueOf(2); // pageType = PageType.CODING

Getting Integer from Enum

On the other hand, to get the integer value from an enum, one can do as follows, by using the getValue method.

ProductType productType = ProductType.DATABASES;
int productTypeId = productType.getValue(); // productTypeId = 3

The getValue method simply returns the internal value of the enum that we store within the value variable.

I hope this helps! Thank you for reading.

Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

15 comments on »Enum to Integer and Integer to Enum in Java«

  1. Juan

    Thanks for your solution Bo, it really helped me!

    Just a comment, I needed to cast the returned object of map.get() to my enum type, in your code it should be:

    public static PageType valueOf(int pageType) {
            return (PageType)map.get(pageType);   //CAST HERE
    }

    That’s how I make it working, thanks again!
    Regards,
    Juan

    • Hello Juan,

      I am happy to hear that this post helped you. Thanks for your positive feedback – and thank you very much for your solution! :-)

  2. Alex

    And what about using this approach:

    public int toInt() {
        return Arrays.binarySearch(values(), this);
    }
    
    public static SomeEnumType fromInt(int i) {
        SomeEnumType[] values = values();
        if (i = values.length) {
            throw new IllegalArgumentException("Out of index!");
        }
        return values[i];
    }
    • Alex

      Parser cuts several letters. It must be next expression in if block: i < 0 || i >= values.length. There are more and less signs must be.

  3. Sameera Nelson

    It seems getting Enum using value of is straightforward.

    Thanks,

    /Sameera

  4. Geert Vancompernolle

    The remark of @Juan is totally correct. A pity the example code is not adapted accordingly yet…

  5. Hello Geert,

    The code has been updated now. Thanks for the reminder! :-)

  6. Andreia

    Really cool guy! :) Good solution!

  7. Martynas

    If you used Map instead of plain Map, there would be no need for the (PageType) cast in the valueOf() method.

  8. Veaceslav CARTERA

    pageType.values() from where you magically get “values()” method? It won’t compile

  9. Douglas Miguel

    This code returns a int value based of position on array (declared values on enum is an array).

    Code:
    PageType.CODING.ordinal();

  10. Alejandro

    Excellent contribution Andersen.
    One observation, If I may, is to check for nullity in your valueOf method, so that you can throw an exception instead of returning null.

    public static PageType valueOf(int value) {
            PageType pageType = (PageType) map.get(value);
            if (pageType == null){
                throw new IllegalArgumentException("Not Enum constant was found for value : " + value);
            }
            return pageType;
        }

    Again, thanks for your easy and clean solution!

  11. jbx

    A better solution to avoid typecasts:

    public enum PageType {
        // ... same as before
       
        private final int value;
        private final static Map map = new HashMap();
    
      // ... same as before
    
       public static PageType valueOf(int pageType) {
            return map.get(pageType);
       }
    
      // ... same as before
    }
  12. Gerrit Brink

    Wrote this implementation. It allows for missing values, negative values and keeps code consistent. The map is cached as well. Uses an interface and needs Java 8.

    Enum

    public enum Command implements OrdinalEnum{
    	PRINT_FOO(-7),
    	PRINT_BAR(6),
    	PRINT_BAZ(4);
    	
    	private int val;
    	private Command(int val){
    		this.val = val;
    	}
    	
    	public int getVal(){
    		return val;
    	}
    	
    	private static Map map = OrdinalEnum.getValues(Command.class);
    	public static Command from(int i){
    		return map.get(i);
    	}
    }

    Interface

    public interface OrdinalEnum{
    	public int getVal();
    	
    	@SuppressWarnings("unchecked")
    	static <E extends Enum> Map getValues(Class clzz){
    		Map m = new HashMap();
    		for(Enum e : EnumSet.allOf(clzz))
    			m.put(((OrdinalEnum)e).getVal(), (E)e);
    		
    		return m;
    	}
    }
  13. Mukul

    public enum AgrudNewsType {
    DIVIDEND(4),CORPORATE_ACTIONS(13);

    private int newsTypeId;
    private static Map map = new HashMap();

    private AgrudNewsType(int newsTypeId) {
    this.newsTypeId = newsTypeId;
    }

    static {
    for (AgrudNewsType agrudNewsType : AgrudNewsType.values()) {
    map.put(agrudNewsType.newsTypeId, agrudNewsType);
    }
    }

    public static AgrudNewsType valueOf(int agrudNewsType) {
    return (AgrudNewsType) map.get(agrudNewsType);
    }

    public int getNewsTypeId() {
    return newsTypeId;
    }
    }

    How do I get the list of all newsTypeIds? like a list of [4,13] in this case?

Leave a Reply

Your e-mail address will not be published.