Antonio SPR
Antonio SPR

Reputation: 37

How to create a map from an array

I have an array of Strings in which each element represents a relationship. I want to pass it to a Map, because it is the logical structure to handle the represented information.

Following these instructions I can do it

How do I create a map from 2 arrays?

fun main() {

    val arrayRules = arrayOf("CH -> B", "HH -> N", "CB -> H", "NH -> C", "MP -> C", "CH -> B", "NH -> C",
        "NN -> C", "BH -> H", "NC -> B", "NB -> B", "BN -> B", "BB -> N", "BC -> B", "CC -> N", "CN -> C")

    val keys = Array<String>(arrayRules.size){i -> arrayRules[i].split(" -> ") [0]}
    val values = Array<String>(arrayRules.size){i -> arrayRules[i].split(" -> ")[1]}
    val rules : Map<String, String> = keys.zip(values).toMap()

    for ((key, value) in rules.entries) {
        println("$key = $value")
    }
}

It seems inelegant to me to have to create two auxiliary arrays to be able to do it. Is there a more direct way of doing it?

Upvotes: 0

Views: 740

Answers (1)

lukas.j
lukas.j

Reputation: 7163

val arrayRules = arrayOf(
  "CH -> B",
  "HH -> N",
  "CB -> H",
  "NH -> C",
  "MP -> C",
  "CH -> B",
  "NH -> C",
  "NN -> C",
  "BH -> H",
  "NC -> B",
  "NB -> B",
  "BN -> B",
  "BB -> N",
  "BC -> B",
  "CC -> N",
  "CN -> C"
)

val result = arrayRules
  .map { it.split(" -> ".toRegex()) }
  .associate { it.first() to it.last() }

println(result)

This will print:

{CH=B, HH=N, CB=H, NH=C, MP=C, NN=C, BH=H, NC=B, NB=B, BN=B, BB=N, BC=B, CC=N, CN=C}

An alternative is, as per @MarkRotteveel's comment above, to use associateBy directly:

val result = arrayRules
  .associateBy({ it.substringBefore(" -> ") }, { it.substringAfter(" -> ") })

Or also:

val result = arrayRules
  .associate { it.substringBefore(" -> ") to it.substringAfter(" -> ") }

Upvotes: 1

Related Questions