程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了列表中的 Kotlin IndexOutOfBoundsException 映射转换大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决列表中的 Kotlin IndexOutOfBoundsException 映射转换?

开发过程中遇到列表中的 Kotlin IndexOutOfBoundsException 映射转换的问题如何解决?下面主要结合日常开发的经验,给出你关于列表中的 Kotlin IndexOutOfBoundsException 映射转换的解决方法建议,希望对你解决列表中的 Kotlin IndexOutOfBoundsException 映射转换有所启发或帮助;

我正在尝试使用 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,ID"

convetToMap(String1) 运行完美,结果 {ID1=1,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
           }
        

大佬总结

以上是大佬教程为你收集整理的列表中的 Kotlin IndexOutOfBoundsException 映射转换全部内容,希望文章能够帮你解决列表中的 Kotlin IndexOutOfBoundsException 映射转换所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。