Load a list of Enums

I have a selectOneMenu like this:

<p:selectOneMenu id="diminui" value="#{naturemb.nature.diminui}" effect="clip">
 <f:selectItems itemLabel="#{naturemb.carregarAtributos()}" itemValue="#{naturemb.carregarAtributos()}" />
</p:selectOneMenu>

I want to display on the screen the values of my Enum:

package br.com.pokemax.modelo;

public enum Atributos {

    HP("HP"), ATTACK("Attack"), DEFENSE("Defense"), SPECIAL_ATTACK("Sp. Attack"), SPECIAL_DEFENSE("Sp. Defense"), SPEED(
            "Speed");

    private String nome;

    private Atributos(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

I created a method in the Controller like this:

public String carregarAtributos() {
        List<Atributos> lista = Arrays.asList(Atributos.values());
        for (int i = 0; i < lista.size(); i++) {
            return lista.get(i).getNome();
        }

        return "";
    }

But it's not working, can anyone help me ?

Author: Roknauta, 2016-11-18

3 answers

Change your method to:

public List<String> carregarAtributos() {
        List<Atributos> lista = Arrays.asList(Atributos.values());
        List<String> retorno = new List<String>();
        for (int i = 0; i < lista.size(); i++) {
           retorno.add(lista.get(i).getNome());
        }
        return retorno;
}
 1
Author: ldeoliveira, 2016-11-18 18:30:18

If you already have an Enum, you can use it without creating a string list. It is better because it facilitates reuse. In your example, just do:

public List<Atributos> carregarAtributos() {
   return Arrays.asList(Atributos.values());
}

And no selectOneMenu:

<p:selectOneMenu id="diminui" value="#{naturemb.nature.diminui}" effect="clip">
   <f:selectItems var="atributo" itemLabel="#{atributo.nome}" itemValue="#{atributo}" value="#{naturemb.carregarAtributos()}"/>
</p:selectOneMenu>

Obs. 1: since vc will use the Enum instead of the string, it has to change the type to Enum tb in the target variable.

Obs. 2: I think it is not necessary to put a setNome in the enum because vc will not be able to change the value at runtime, only in creation (in Atributos(String nome)).

 2
Author: Marcus Martins, 2016-11-19 02:08:42

Douglas,

The easiest way to return the list of enums is:

public EnumSet<Atributos> listarAtributos() {
    return EnumSet.allOf(Atributos.class);
}

Hope it helps;)

Hug!

 1
Author: ℛɑƒæĿᴿᴹᴿ, 2016-12-06 19:15:10