Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce a list of enum keys/names in groovy

Tags:

enums

groovy

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)
}
like image 434
TriumphST Avatar asked Oct 22 '15 16:10

TriumphST


2 Answers

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.

like image 145
mnd Avatar answered Nov 22 '22 06:11

mnd


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() }
like image 36
Swaps Avatar answered Nov 22 '22 08:11

Swaps