Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Lambda expression to iterate over enum values and initialize final member

I have a static enum like this:

private static enum standardAttributes {
    id, gender, firstname, lastname, mail, mobile
}

I need all the values as String. Therefore I have a method like this:

public static List<String> getStandardRecipientsAttributes() {
    List<String> standardAttributesList = new ArrayList<String>();
    for (standardAttributes s : standardAttributes.values())
        standardAttributesList.add(s.toString());

    return standardAttributesList;
}

There is no need to create the same List everytime this method is called. So I created a static member:

static final List<String> standardAttributesList;
static {
    standardAttributesList = getStandardRecipientsAttributes();
}

This is all fine, but I wonder if there is a fancy Lambda expression to replace the method. Something like this:

Arrays.asList(standardAttributes.values()).forEach((attribute) -> standardAttributesList.add(attribute.toString()));

Two questions:

  1. Can I avoid the Arrays.asList wrapper?
  2. How can I handle the compiler error: The blank final field standardAttributesList may not have been initialized?
like image 428
s.meissner Avatar asked Mar 25 '15 09:03

s.meissner


People also ask

How do I iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Can you loop through enum Java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


1 Answers

You can do

static final List<String> standardAttributesList = 
                                           Stream.of(values())
                                                 .map(Enum::name)
                                                 .collect(Collectors.toList());

This will create a Stream from an the array of values, apply the .name() method to each one and finally collect all the results into a List.

like image 114
Peter Lawrey Avatar answered Oct 02 '22 16:10

Peter Lawrey