arnab arnab - 29 days ago 7
Java Question

How to use `filter` on Map instance in Kotlin?

I see that

is defined on
Map
, but I am not able to figure out how to use it. Anyone care to share an example?

I have a deeply nested TreeMap instance (
TreeMap<String, Map<String, Map<*, *>>>
) and I want to
filter/find
the first (which is the only in the domain) top-level key that has a certain characteristics associated with something deeper in the value.

Here's how the data looks like:

{
"i1": {
"aliases": {}
},
"i2": {
"aliases": {}
},
"i3": {
"aliases": {}
},
"i4": {
"aliases": {
"alias-im-looking-for": {}
}
}
}


I have this following non-functional code which solves it right now:

val indexToAliasMappingType = LinkedTreeMap<String, Map<String, Map<*, *>>>()
val indexToAliasMappings = Gson().fromJson(response.jsonString, indexToAliasMappingType.javaClass)

var currentIndexName = ""
for ((index, aliasMappings) in indexToAliasMappings) {
val hasCurrentAlias = aliasMappings.get("aliases")?.containsKey(alias)
if (hasCurrentAlias != null && hasCurrentAlias) {
currentIndexName = index
}
}

return currentIndexName

Answer

Looks like what you need is the key part of the first entry that matches your criteria. Something like this (single line intentional) should help:

val currentIndexName = indexToAliasMappings.filterValues { it["aliases"]?.containsKey(alias) ?: false }.keys.firstOrNull() ?: ""