I am looking to create Map<Integer, EmployeeReport> using the below lambda. Is there a clean way to do this in Kotlin? What I essentially need to do is an associateWith operation but filtering out all null values that would be returned.
employeeById.keys.associateWith {
val employeeData = getEmployeeData()
if(employeeData == null){ null }
else { EmployeeReport(employeeData) }
}
I feel like I could accomplish what I am looking for with the below code, but I'm wondering if there is a cleaner way.
employeeById.keys.mapNotNull{
val employeeData = getEmployeeData()
if(employeeData.isNull()){ null }
else { Pair(it, EmployeeReport(employeeData)) }
}.associate { it.first to it.second }
Thank you. Any advice is appreciated.
CodePudding user response:
One option would be to use toMap()
(as @Tenfour04 suggested) and simplify the if else
, like below
employeeById.keys.mapNotNull { key ->
getEmployeeData()?.let { key to EmployeeReport(it) }
}.toMap()
Another option would be to define a function similar to the associateWith
funtion of Kotlin with Kotlin's buildMap
(ref) builder function
inline fun <K, V> Iterable<K>.associateWithNotNull(
valueTransform: (K) -> V?,
): Map<K, V> = buildMap {
for (key in this@associateWithNotNull) {
val value = valueTransform(key) ?: continue
this[key] = value
}
}
and then using it as
employeeById.keys.associateWithNotNull { key ->
getEmployeeData()?.let { EmployeeReport(it) }
}