How to save enum value 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 the enum values Some value1 , Some value2 and Some ArrayList in an ArrayList .

I can get all the values ​​in the array using SomeEnum.values() and SomeEnum.values() over this 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, for example values() , that returns an array Some value1 , Some value2 and Some value3 ?

+7
java arraylist arrays enums
source share
3 answers

You can create this list inside enum itself as follows:

 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(); 
+9
source share

If you are using Java 8 and cannot change the enumeration:

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

You can simply create a list from an array as follows:

 List<String> list = Arrays.asList(SomeEnum.values()); 
+2
source share

All Articles