sxtanna
02/03/2018, 10:22 PMtoMap()
function available as an extension on a collection of Map.Entry<K, V>
?Andreas Sinz
02/04/2018, 9:54 AMThese Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator
(https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html). That means you are not able to create a new Map from List<Map.Entry<K, V>>
, because they are short-lived instances. So you need to create new `Pair<K, V>`s and use them to construct a new mapsxtanna
02/04/2018, 10:27 AMsxtanna
02/04/2018, 10:27 AMsxtanna
02/04/2018, 10:28 AMsxtanna
02/04/2018, 10:28 AMsxtanna
02/04/2018, 10:29 AMsxtanna
02/04/2018, 10:30 AMAndreas Sinz
02/04/2018, 10:43 AMfun <K, V, R, T> Iterator<Map.Entry<K, V>>.toMap(keyTransform: (K) -> R, valueTransform: (V) -> T): Map<R, T> {
var map = mutableMapOf<R, T>()
this.forEach { entry ->
map.put(keyTransform(entry.key), valueTransform(entry.value))
}
return map
}
sxtanna
02/04/2018, 10:50 AMfun <K, V> Iterable<Map.Entry<K, V>>.toMap() : Map<K, V> {
val map = mutableMapOf<K, V>()
this.forEach { map.put(it.key, it.value) }
return map
}
Andreas Sinz
02/04/2018, 10:51 AMsxtanna
02/04/2018, 10:52 AMsxtanna
02/04/2018, 10:52 AMsxtanna
02/04/2018, 10:52 AMsxtanna
02/04/2018, 10:53 AMmap.entries.sortedBy { it.key }.sortedBy { it.value }
But this leaves you with List<Map.Entry<K, V>>
sxtanna
02/04/2018, 10:54 AMList<Pair<K, V>>
in order to access the toMap()
functionAndreas Sinz
02/04/2018, 10:57 AMsxtanna
02/04/2018, 11:00 AMsxtanna
02/04/2018, 11:00 AMsxtanna
02/04/2018, 11:01 AMAndreas Sinz
02/04/2018, 11:03 AMsxtanna
02/04/2018, 11:05 AMilya.gorbunov
02/05/2018, 1:06 AMassociate
and associateBy
extensions to create a map from any iterable, for example:
map.entries.associateBy({ it.key }, { it.value })
sxtanna
02/05/2018, 1:10 AMtoMap()