Kotlin ignore null keys on map

Viewed 815

I have a list of objects that looks like that:

class Attachment(
        val attachmentId: Int,
        val attachmentName: String?,
        val size: Long
)

I wanna have a hash map that uses the attachmentName as the key and the whole class as the value.

The issue is that the attachmentName can be null, I wanna ignore these items (with null on attachmentName so that they wont appear on the hash map)

I wanna know if there's an elegant was to do it in Kotlin Thanks

2 Answers

If you mean that you don't want to add them to the map in the first place, then just filter them out before adding, e.g.:

val map = myAttachments.filter{ it.attachmentName != null }
                       .associateBy{ it.attachmentName!! }

This is a bit ugly, as the associateBy() doesn't know that the attachmentName can't be null, so if you want the map's key type to be non-nullable you have to force it with !!.

Another approach would be to do the filtering at the same time as creating the mappings:

val map = myAttachments.mapNotNull {
        if (it.attachmentName != null)
            attachmentName to it
        else
            null
    }.toMap()

…but that's longer and creates more temporary objects.

Note that some map implementations don't support null keys, so the alternative of creating the map and then removing items with a null key is risky and would depend upon the exact implementation.

use filterKeys

myHashMap.filterKeys { it != null }
Related