I am trying to figure out the best way to map my sorted map to the arguments of another function. This is an example of what I have.
data class ValueDescription (val length: Int, val count: Int)
// Now I am trying to map to a variable that looks like this
// This variable cannot be changed, I have to return this variable in this format
// The output will be a list of ValueDescriptions with a length and count for each entry of the map I have
// I will add the results of myValues to a mutable list later
val myValues = ValueDescription(_length here__, __count here__)
I have a sorted map that I want to map to my values
// The map will look like this
// Where both Ints hold the lengths and counts
// For example I would have the length of 7 to count of 8
val out = Map<Int, Int>
How can I take the values in my sorted map and place them into the variable myValues?
I tried to map by looping through my map with the forEach method and doing something like
out.map{it.key to myValues.ValueDescription.length}
but this doesn't seem to work.
CodePudding user response:
I'm not sure I completely understood the question. If I got it correctly, your input is the Map<Int, Int>
and you want to transform it to a List<ValueDescription>
.
You can definitely use the map
function for this:
val inputMap: Map<Int, Int> = TODO("provide the initial map here")
val myValues = inputMap.map { (l, c) -> ValueDescription(l, c) }
The map
function here iterates over the entries of the map, and transforms each of them into a value of type ValueDescription
by calling our lambda (the part between braces { ... }
).
Each entry of the map here contains a key (the length) and a value (the count). Instead of using it.key
and it.value
, you can also use parentheses like I did here with (l, c)
to destructure the entry into its 2 parts and give them names like l
and c
. The above is equivalent to:
val myValues = inputMap.map { ValueDescription(it.key, it.value) }