Reputation: 35
Iam trying to convert a Dynamic string to map using kotlin associate()
transformation and its working properly
Since my query string is Dynamic, sometimes it might not contain required data and thus throwing 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)
runs perfectly and results {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
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
Upvotes: 1
Views: 567
Reputation: 31670
You could filter
before associating, if you just want to eliminate the bad inputs:
fun convetToMap(val data: String) : Map<String, String> =
data.split(",")
.filter { it.contains("=") }
.associate { str ->
str.split("=").let {
(key, value) -> key to value
}
Upvotes: 3