alexa

Order ArrayList with Int and String in Kotlin Android ?

Order ArrayList with Int and String in Kotlin Android ?

the problem is that you have "Jack" two times in it. things.set(things.indexOf("Jack"), 11); only changes the first one to 11, not the second one.

 val things = arrayOf<Any>("Jack", 8, 2, 6, "King", 5, 3, "Queen", "Jack");
things.set(things.indexOf("Jack"), 11);
things.set(things.indexOf("Queen"), 12);
things.set(things.indexOf("King"), 13);
println(things.contentToString()) //prints [11, 8, 2, 6, 13, 5, 3, 12, Jack] 

Now, how I maybe would do it, is like this:

 fun main() {
    val things = arrayOf("Jack", 8, 2, 6, "King", 5, 3, "Queen", "Jack")
    things.sortWith(compareBy { it.toInt() })
    println(things.contentToString()) //prints [2, 3, 5, 6, 8, Jack, Jack, Queen, King]
}

val mapping = mapOf("Jack" to 11, "Queen" to 12, "King" to 13)

fun Any.toInt() : Int {
    if (this is Int) return this
    return mapping[this] ?: 0
}

252 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online

Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry