Search code examples
kotlincollections

Check occurance of set of enums identifier in a JSON?


I have an enum class like:

enum class MimeType(val value: String, val priority: Int) {
    PNG("PNG", 1),
    GZIP("GZIP", 2),
    TEXT("TEXT", 3),
    Unknown("null", Int.MIN_VALUE)
}

and an example set of that enum:

val mimeTypeSet = setOf(MimeType.PNG, MimeType.GZIP)

Further I have a JSON object, which contains an array of objects, each with a "name" identifier:

"documentProfile": {
            "types": [{
                "name": "png",
                "title": "Picture1",
                "description": "Picture of animal",
                "hash": fedac987343,
            }, {
                "name": "gzip",
                "title": "file1",
                "description": "document of ra",
                "hash": 8a73f43edc,
            }]
        }

what I acces in code like:

documentProfile.types.forEach{ type ->
    type.name // iterate through png, gzip, etc.
}

So how can I check for type.name which is "png" of type String if it occurs in mimeTypeSet of that enums?


Solution

  • You can use this:

    documentProfile.types.forEach { type ->
        val mimeType = mimeTypeSet.firstOrNull {
            it.value.contentEquals(type.name, true)
        }
    }
    

    mimeTypeSet.firstOrNull returns the first entry of the set that satisfies the condition that follows. The condition tests if the enum's value is the same as type's name while ignoring upper or lower case.

    mimeType then contains the enum that was found or null if nothing matched.