Kotlin IndexOutOfBoundsException on list to map 转换

Kotlin IndexOutOfBoundsException on list to map convertion

我正在尝试使用 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) 运行s 完美,结果 {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() 来解决这个问题,我试过使用条件但无法帮助解决

如果您只是想消除错误的输入,您可以 filter 在关联之前:

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