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:
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.
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With