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

I have the following listing 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 create an ArrayList <String> of keys or values

What I'm doing now is iterating over all the elements and creating a list of arrays, but I think there should be an easy 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)
}
+4
source share
1 answer

ArrayList of keys

ImageTypes.values()*.name()

ArrayList values

ImageTypes.values()*.value

There are two things here.

1) I use the distribution operator to trigger an action for each entry in the collection (although in this case it's just an array) that references are used name()and value.

2) name() ( ), ( ) , value ImageTypes .

+7

Source: https://habr.com/ru/post/1612800/


All Articles