Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store value of enum in arraylist?

I have an enum like this:

public enum SomeEnum 
{
    ENUM_VALUE1("Some value1"),
    ENUM_VALUE2("Some value2"),
    ENUM_VALUE3("Some value3");
}

I need to store values of enum Some value1, Some value2 and Some value3 in an ArrayList.

I can get all values in an array using SomeEnum.values() and iterate over that array and store the value in an ArrayList like this:

SomeEnum values[] = SomeEnum.values();
ArrayList<SomeEnum> someEnumArrayList = new ArrayList<SomeEnum>();
for(SomeEnum value:values) 
{
    someEnumArrayList.add(value.getValue());
}

Is there any other method like values() that returns array of Some value1, Some value2 and Some value3?

like image 217
वरुण Avatar asked Aug 19 '15 07:08

वरुण


People also ask

Can we use enumeration in ArrayList?

In order to get enumeration over ArrayList with Java Collections, we use the java. util. Collections. enumeration() method.

Can we create List of enums?

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum. Great insight in this answer!

Can ArrayList store different data types?

ArrayList is a kind of List and List implements Collection interface. The Collection container expects only Objects data types and all the operations done in Collections, like iterations, can be performed only on Objects and not Primitive data types. An ArrayList cannot store ints.

Can enums hold values?

Overview. The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.


2 Answers

You could build that list inside the enum itself like this:

public enum SomeEnum {

    ENUM_VALUE1("Some value1"),
    ENUM_VALUE2("Some value2"),
    ENUM_VALUE3("Some value3");

    private static final List<String> VALUES;

    private final String value;

    static {
        VALUES = new ArrayList<>();
        for (SomeEnum someEnum : SomeEnum.values()) {
            VALUES.add(someEnum.value);
        }
    }

    private SomeEnum(String value) {
        this.value = value;
    }

    public static List<String> getValues() {
        return Collections.unmodifiableList(VALUES);
    }

}

Then you can access this list with:

List<String> values = SomeEnum.getValues();
like image 180
Tunaki Avatar answered Sep 17 '22 15:09

Tunaki


If you're using Java 8 and cannot change the enum:

List<String> list = Stream.of(SomeEnum.values())
                          .map(SomeEnum::getValue)
                          .collect(Collectors.toList());
like image 22
Flown Avatar answered Sep 17 '22 15:09

Flown