Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum values as List of String in Java 8

Tags:

java

enums

java-8

Is there any Java 8 method or easy way, which returns Enum values as a List of String, like:

List<String> sEnum = getEnumValuesAsString(); 
like image 629
Suganthan Madhavan Pillai Avatar asked Apr 06 '15 05:04

Suganthan Madhavan Pillai


People also ask

How do I get a list of all enum values?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.

Can you have an ArrayList of enums?

You can create a list that holds enum instances just like you would create a list that holds any other kind of objects: ? List<ExampleEnum> list = new ArrayList<ExampleEnum>(); list.


2 Answers

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values()); 

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class)); 

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())                                .map(Enum::name)                                .collect(Collectors.toList()); 
like image 161
Konstantin Yovkov Avatar answered Oct 20 '22 12:10

Konstantin Yovkov


You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN}; EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList()) 

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList()) 

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" }) public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {     Set<String> notAllowedNames = enumNames.stream()             .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))             .collect(Collectors.toSet());      if (notAllowedNames.size() > 0) {         String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()             .collect(Collectors.joining(", "));          throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()                 .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "                 + "of the following : " + validEnumNames);     } } 

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

like image 30
Raf Avatar answered Oct 20 '22 11:10

Raf