Home > Software engineering >  Extracting items from a Map using a step
Extracting items from a Map using a step

Time:12-07

In Kotlin you can extract list items using a step like this:

val numbers = listOf("one", "two", "three", "four", "five", "six")    
println(numbers.slice(0..4 step 2))

Is there a similar way to do this for a map? So instead of listOf, I'm using mapOf.

CodePudding user response:

First you need to think about whether it makes sense to use slice on a Map. The Map interface does not guarantee an order, so it does not have the concept of indices that you can select from, which is what slice does.

If your Map is backed by a specific implementation that guarantees an iteration order, such as LinkedHashMap, then it can make sense to convert the Map's entries into a List so you can slice them, and then you can convert the result back to a Map.

val result = someLinkedHashMap
  .entries
  .toList()
  .slice(someRange)
  .associate { it.key to it.value } // change the filtered entries list into a new map

The associate function's documentation guarantees a Map implementation that has consistent execution order.

CodePudding user response:

slice() is an extension function for Arrays and Lists.

To convert a Map to a List, first get the entries Set, and then convert the Set into a List.

Run in Kotlin Playground

fun main() {
  val numbers = mapOf(
    "one" to 1, 
    "two" to 2, 
    "three" to 3, 
    "four" to 4, 
    "five" to 5, 
    "six" to 6,
  )

  // get the Map entries, and convert them to a List - then slice
  val sliced = numbers.entries.toList().slice(0..4 step 2)

  println(sliced)
}

Output:

[one=1, three=3, five=5]
  • Related