大佬教程收集整理的这篇文章主要介绍了列表中的 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,请注明来意。