arnab arnab - 1 year ago 108
Java Question

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

I see that

is defined on
, 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
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 Source

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() ?: ""
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download