Colton Idle
04/11/2022, 10:51 PMval data =
hashMapOf(
"firstName" to firstName,
"lastName" to lastName)
but I wanted to not add firstName or lastName to the hashmap if they are null. What would be the best way to do that?ephemient
04/11/2022, 10:58 PMJoffrey
04/11/2022, 10:58 PMjava.util.HashMap as output? In general it's more common to stick with mapOf or mutableMapOf.
When building a read-only map, you can use buildMap with conditions inside:
val map = buildMap {
firstName?.let { put("firstName", it) }
lastName?.let { put("lastName", it) }
}
If what you need is a mutable map, you can also add stuff conditionally with `apply`:
val map = mutableMapOf<String, String>().apply {
firstName?.let { put("firstName", it) }
lastName?.let { put("lastName", it) }
}Colton Idle
04/11/2022, 11:00 PMephemient
04/11/2022, 11:01 PMbuildMap {
firstName?.let { put("firstName", it) }
lastName?.let { put("lastName", it) }
}
@Suppress("UNCHECKED_CAST")
fun <K, V> Map<K, V?>.filterNotNullValues(): Map<K, V> = filterValues { it != null } as Map<K, V>
mapOf("firstName" to firstName, "lastName" to lastName).filterNotNullValues()ephemient
04/11/2022, 11:03 PMThe data passed into the trigger can be any of the following types:
• Any primitive type, including null, int, long, float, and boolean.
•String
•, where the contained objects are also one of these types.List<?>
•, where the values are also one of these types.Map<String, ?>>
•JSONArray
•JSONObject
•you do not need a HashMap, that Kotlin example was simply translated from JavaNULL
Colton Idle
04/11/2022, 11:03 PMephemient
04/11/2022, 11:05 PMmapOfNotNull just to match listOfNotNull better, but yeah that can also be doneColton Idle
04/11/2022, 11:05 PMephemient
04/11/2022, 11:05 PMephemient
04/11/2022, 11:05 PMephemient
04/11/2022, 11:06 PMColton Idle
04/11/2022, 11:09 PMfun <K: Any, V: Any> nonNullHashMapOf(vararg entries: Pair<K?, V?>) {
val map = HashMap<K, V>()
for ((key, value) in entries) {
map[key ?: continue] = value ?: continue
}
}
should I try to use a Regular map internally, or is HashMap alright?ephemient
04/11/2022, 11:10 PMhashMapOf it should probably return a HashMap to reduce confusion 😛ephemient
04/11/2022, 11:11 PMMutableMap is backed by a LinkedHashMap, so it is a HashMap in a senseephemient
04/11/2022, 11:11 PMColton Idle
04/11/2022, 11:13 PMfun <K: Any, V: Any> mapOfNotNull(
vararg entries: Pair<K?, V?>
): HashMap<K, V> {
val map = HashMap<K, V>()
for ((key, value) in entries) {
map[key ?: continue] = value ?: continue
}
return map
}Colton Idle
04/11/2022, 11:15 PMColton Idle
04/11/2022, 11:19 PMColton Idle
04/11/2022, 11:20 PMLandry Norris
04/12/2022, 9:39 PM