【问题标题】:Kotlin : string to array to key valueKotlin:字符串到数组到键值
【发布时间】:2019-05-13 12:03:05
【问题描述】:

我正在尝试创建一个 key => value Hashmap。

首先,我有一个由 <br /> 分隔的字符串。然后,我用 split() 拆分它(以独立获取每个字符串)。

然后,我需要用 "=" 分割每个结果。第一部分是键(我需要它是一个字符串),第二部分是值(一个 int)

现在我有

val formules = objInput.getString(Constants.formules)
val hashmap = HashMap<String, Int>()
val resSplit = formules.split("<br />")
    resSplit.forEach {
      val splitFormule = it.split(" = ")
      val key = splitFormule.elementAt(0)
      val value = splitFormule.elementAt(1)
      Log.i(TAG, "$key")
}

当我尝试显示值时出现此错误:

索引:1,大小:1

【问题讨论】:

  • 在某个时间点splitFormule 只包含一个元素。检查一下。
  • 你期待什么?你可能想调试它,你会看到问题......可能是你的字符串不包含任何 ` = `?
  • 是的@Rolan,就是这样。它忘记添加这个条件。谢谢,我觉得有点傻^^'

标签: arrays string kotlin hashmap


【解决方案1】:

请注意您的输入是否正确。空格是相关的。 &lt;br /&gt; 不一样 来自&lt;br/&gt;=&lt;space&gt;=&lt;space&gt; 不同。假设您的输入如下所示:

foo = 3<br />bar = 5<br />baz = 9000

然后您可以使用这个简单的表达式创建地图:

val map = formules
    .splitToSequence ("<br />") // returns sequence of strings: [foo = 3, bar = 5, baz = 9000]
    .map { it.split(" = ") } // returns list of lists: [[foo, 3 ], [bar, 5 ], [baz, 9000]]
    .map { it[0] to it[1] } // return list of pairs: [(foo, 3), (bar, 5), (baz, 9000)]
    .toMap() // creates a map from your pairs

【讨论】:

  • 你可能想使用splitToSequence而不是split,否则你会在每个map调用上创建一个新列表,当你调用toMap时你基本上会丢弃所有的列表...
  • 非常感谢@Roland!我没有意识到这一点。让我读了这篇关于集合与序列的有趣文章:blog.kotlin-academy.com/…
【解决方案2】:

正如您已经说过的,您忘记了检查字符串是否包含= 的条件。

进一步说明:您也可以将 elementAt 替换为 getindexing operator(例如 splitFormule[0])。

您可能还对destructuring 感兴趣,例如你的拆分也可以写成如下:

val (key, value) = it.split(" = ") // no need to extract the values from the array, if you know how the splitted data looks like
// you may even want to use the following if there could potentially be more than 1 '=' in the value part
val (key, value) = it.split(" = ", limit = 2) // at most 2 parts

最后是另一个变体,如果没有任何关联的值,它会跳过键:

val yourMap = formules.splitToSequence("<br />")
    .filter { it.contains("=") }
    .map { it.split("""\s*=\s*""".toRegex(), limit = 2) }
    .map { (key, value) -> key to value } // destructuring
    .toMap()

// or: instead of filtering do a takeif and if you require those keys, do something appropriate there (e.g. set a default value instead)
val yourMap = formules.splitToSequence("<br />")
    .map { it.split("""\s*=\s*""".toRegex(), limit = 2) }
    .mapNotNull { it.takeIf { it.size == 2 } } // this discards now the entries without any value
    .map { (key, value) -> key to value } // destructuring
    .toMap()

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2017-04-15
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多