After I map through one Set, I have to explicitly cast it back to Set. For example:
fun getNewSet(oldSet: Set<String>): Set<String> { return oldSet .map{ getNewStringFromOld(it) } .toSet() }
What is the proper way to map through the set without explicitly casting it back to Set?
To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map.
kotlin.Any. ↳ android.util.ArrayMap. ArrayMap is a generic key->value mapping data structure that is designed to be more memory efficient than a traditional java.
The kotlin mapOf is defined as the function and it is one of the util collections and it is denoted under the interface it accepts keys and values for the user-defined types the key based mapped values are processing at the capabilities for to store and retrieving the values with the help of specific keys it also been ...
Looking at the library code, the only other way to do this would be to call mapTo
which takes a destination collection:
oldSet.mapTo(HashSet<String>()) { getNewStringFromOld(id) }
I'm not sure the default is wrong. The problem is that map
might be used in a way that results in a list of non-unique values. If there was a special version of Set.map()
that returned a set, you couldn't use map in that way - any non-unique value would replace the value in the result. I could certainly see the case being made that map
should always result in a collection that is the same size as the source collection, and if map
created a Set
, this wouldn't always be the case.
If you do this often, perhaps just create your own extension function:
public inline fun <T, R> Iterable<T>.mapToSet(transform: (T) -> R): Set<R> { return mapTo(HashSet<R>(), transform) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With