I have the following enum in groovy
public enum ImageTypes {
jpg ("image/jpeg"),
jpeg ("image/jpeg"),
jpe ("image/jpeg"),
jfif ("image/jpeg"),
bmp ("image/bmp"),
png ("image/png"),
gif ("image/gif"),
ief ("image/ief"),
tiff ("image/tiff"),
tif ("image/tiff"),
pcx ("image/pcx"),
pdf ("application/pdf"),
final String value
ImageTypes(String value) {
this.value = value
}
String getValue() {
return this.value
}
String toString(){
value
}
String getKey() {
name()
}
}
and I want to produce an ArrayList<String> of the keys or the values
What I am currently doing is looping through all the items and building the array list, but I'm thinking there has got to be a simple way to do this...
def imageTypes = ImageTypes.values()
def fileExts = new ArrayList<String>()
def mimeTypes = new ArrayList<String>()
for (type in imageTypes) {
fileExts.add(type.key)
mimeTypes.add(type.value)
}
ArrayList of keys
ImageTypes.values()*.name()
ArrayList of values
ImageTypes.values()*.value
There are two things to point out here.
1) I'm using the spread operator to call an action on each entry in a collection (although this case it's just an array), that's how the name()
and value
references are used.
2) I'm calling name()
with parenthesis (as a method) because (I believe) it is an implicit attribute on the enum, whereas I'm just using the value
attribute directly from the ImageTypes
object for the values.
Expanding @mnd's answer -
The Spread Operator
is the best choice, but if you're using Jenkins this won't work as is. To run the Spread Operator
you will need to add @NonCPS
in the Jenkins Pipeline DSL
.
Another way to the list of enum
keys is to directly use its Enumeration features.
ImageTypes.values().collect() { it.name() }
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