Best way to get Enum from its entire ID value in Java

0

A cordial greeting.

I have an ENUM in the following way

public enum EnumNumeros
{
    UNO(1),
    DOS(2),
    TRES(3);

    private int id;

    private EnumNumeros(int id)
    {
        this.id = id;
    }

    public int getId()
    {
        return id;
    }
}

In my application I want, from the whole value, for example 2, that the Enum object be returned to me: EnumNumeros.DOS

This I do it in the following way:

public static EnumNumeros getNumeroEnum(ObjetoJava objetoJava)
{
    EnumNumeros enumDevolver = null;


    int id = objetoJava.getObjetoNumero().getId();

    for(EnumNumero enumTemp: EnumNumero.values())
    {
        if(id == enumTemp.getId())
        {
            enumDevolver = enumTemp;
            break;
        }
    }

    return enumDevolver;
}

BUT

I wonder if there is a more direct way to achieve my goal, since the Enums have an elegant method to, from the description of the value Enum return to ENUM as such

EnumNumeros.valueOf( cadena_de_texto )

There should be some more elegant way of, from the ID value in my case, return the corresponding ENUM.

Thank you very much for your help.

    
asked by samz550a 26.01.2018 в 18:06
source

1 answer

1

By default there is no direct way, but you can implement a static method in each enum in which you need a search for some attribute instead of its name.

In particular I got used to doing it with a map in the same enum. But you could do it with a for.

public enum EnumNumeros {
    UNO(1), DOS(2), TRES(3);
    private int id;
    private static final Map<Integer, EnumNumeros> MAP = new HashMap<>();
    private EnumNumeros(int id) { this.id = id; }
    public int getId() { return id; }
    public static EnumNumeros fromId(int id){
        return MAP.get(id);
    }
    static{
        for(EnumNumeros n : values()){
            MAP.put(n.getId(), n);
        }
    }
}
    
answered by 26.01.2018 / 23:40
source