简体   繁体   English

Kotlin IndexOutOfBoundsException 列表到 map 转换

[英]Kotlin IndexOutOfBoundsException on list to map convertion

Iam trying to convert a Dynamic string to map using kotlin associate() transformation and its working properly我正在尝试使用 kotlin associate()转换将动态字符串转换为 map 及其正常工作

Since my query string is Dynamic, sometimes it might not contain required data and thus throwing IndexOutOfBoundsException由于我的查询字符串是动态的,有时它可能不包含所需的数据,因此会抛出 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" 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) runs perfectly and results {id1=1, id2=2, id3=3, id4=4, id5=5} convetToMap(string1)运行完美,结果{id1=1, id2=2, id3=3, id4=4, id5=5}

when i'm trying to run convetToMap(string2) it throws IOB Exception and the logcat says当我试图运行convetToMap(string2)它抛出 IOB Exception 并且 logcat 说

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

is there a way to resolve this by using assocaite(), i have tried using conditions but that couldn't help to solve有没有办法通过使用 assocaite() 来解决这个问题,我尝试过使用条件,但无济于事

You could filter before associating, if you just want to eliminate the bad inputs:如果您只想消除不良输入,则可以在关联之前进行filter

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM