【问题标题】:Kotlin IndexOutOfBoundsException on list to map convertion列表到地图转换上的 Kotlin IndexOutOfBoundsException
【发布时间】:2021-08-06 18:27:17
【问题描述】:

我正在尝试使用 kotlin associate() 转换将动态字符串转换为映射及其正常工作

由于我的查询字符串是动态的,有时它可能不包含所需的数据,从而引发 IndexOutOfBoundsException

fun convetToMap(val data: String) : Map<String, String> {
    return data.split(",").associate { str ->
           str.split("=").let { 
              (key, value) -> key to value
           }
    }
}

val string1 = "id1=1,id2=2,id3=3,id4=4,id5=5" val string2 = "id1=1,id2=2,id3=3,id4=4,id"

convetToMap(string1) 运行完美,结果{id1=1, id2=2, id3=3, id4=4, id5=5}

当我尝试运行 convetToMap(string2) 时,它会抛出 IOB 异常并且 logcat 会说

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
 at java.util.Collections$SingletonList.get (Collections.java:4815) 

有没有办法通过使用 assocaite() 来解决这个问题,我尝试过使用条件但无济于事

【问题讨论】:

  • 第二个输入无效,它会导致split("=") 生成单个元素的数组并导致异常。在此fun 中使用输入之前,您必须提供默认值或检查输入是否格式正确。顺便说一句,data 是一个 Kotlin 关键字,我不会将其用作参数名称...

标签: java android list kotlin collections


【解决方案1】:

如果您只是想消除不良输入,您可以在关联之前filter

fun convetToMap(val data: String) : Map<String, String> =
    data.split(",")
        .filter { it.contains("=") }
        .associate { str ->
           str.split("=").let { 
              (key, value) -> key to value
           }
        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 2016-01-01
    • 1970-01-01
    • 2011-10-20
    • 2020-11-20
    • 1970-01-01
    • 2020-05-11
    • 2020-07-06
    相关资源
    最近更新 更多