Xuc Xiem
06/23/2020, 11:21 AMIterable<A>
and want to create a Map<A, Int>
with a function f: A -> Int?
. The values in the map cannot be null. So I write something like this:
iterable
.map { Pair(it, f(it)) } // Iterable<Pair<A, Int?>>
.filter { it.second != null } // still Iterable<Pair<A, Int?>> but we can be sure the Int is not null
.map { Pair(it.first, it.second!!) } // now it is Iterable<Pair<A, Int>>
.toMap()
Is there any better way?Chantry Cargill
06/23/2020, 11:23 AMiterable.mapNotNull { thing ->
f(thing)?.let { thing to it }
}
James Fagan
06/23/2020, 11:26 AMiterable
.associateWith { f(it) }
.filterValues { it != null }
diesieben07
06/23/2020, 11:26 AMMap<A, Int?>
instead of Map<A, Int>
James Fagan
06/23/2020, 11:29 AMMap<A, Int>
James Fagan
06/23/2020, 11:29 AMiterable
.associateWith { f(it) }
.filterValues { it != null }
.mapValues { it ?: 0 }
diesieben07
06/23/2020, 11:29 AMJames Fagan
06/23/2020, 11:31 AMXuc Xiem
06/23/2020, 11:54 AMiterable.mapNotNull { thing -> f(thing)?.let { thing to it } }
is excellent. I always wonder what's the equivalent of Scala's .collect
in Kotlin. mapNotNull ?.let
might not be that powerful but good enough.diesieben07
06/23/2020, 11:55 AMmapNotNull
is the closest equivalent