15

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?

1
  • Just use Arrays.asList(values) which returns a list. Commented Aug 19, 2015 at 7:32

3 Answers 3

13

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();
Sign up to request clarification or add additional context in comments.

1 Comment

How to check the Arraylist of enum contains value or not ?
6

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

List<String> list = Stream.of(SomeEnum.values())
                          .map(SomeEnum::getValue)
                          .collect(Collectors.toList());

Comments

3

You can simply create list from array like this:

List<String> list = Arrays.asList(SomeEnum.values());

1 Comment

This will return a List though, not an ArrayList. Lists aren't implementing all methods, e.g. remove won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.