8

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)
}
TriumphST
  • 1,194
  • 1
  • 10
  • 17

2 Answers2

15

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.

mnd
  • 2,709
  • 3
  • 27
  • 48
  • Worked great! I knew there had to be an easy way in groovy! – TriumphST Oct 22 '15 at 19:49
  • 1
    http://www.groovy-lang.org/style-guide.html#_getters_and_setters You're actually calling the getter method for value. Name doesn't follow the getter/setter format so it can't use Groovy's shorthand – ScientificMethod Oct 22 '15 at 20:46
5

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() }
Swaps
  • 1,450
  • 24
  • 31