Home > database >  Find index of Custom List - Kotlin
Find index of Custom List - Kotlin

Time:10-01

I have a list

val SongList = [SongInfo(name=Dark Star, rawId=2131689475, time=1:30), SongInfo(name=Can't let go, rawId=2131689474, time=1:24), , SongInfo(name=Big Digits, rawId=2131689473, time=0:49), SongInfo(name=What's Mine, rawId=2131689478]

and to get the song name I do this

val song = songList[0].name

shuffling song

songList.shuffle()

how do I find an index of song, after shuffling the list?

CodePudding user response:

My code isn't the best solution but it finds the index, and return the song name by index.

data class SongInfo(var name: String, var rawId: String, var time: String)

fun main() {
    val songList = listOf(
        SongInfo(name = "Dark Star", rawId = "2131689475", time = "1:30"),
        SongInfo(name = "Can't let go", rawId = "2131689474", time = "1:24"),
        SongInfo(name = "Big Digits", rawId = "2131689473", time = "0:49"),
        SongInfo(name = "What's Mine", rawId = "2131689478", time = "22:31")
    )
    val song = songList[0].name
    val shuffledSongList = songList.shuffled()
    println(shuffledSongList)
    var index = 0
    while (true) {
        if (shuffledSongList[index].name == song) break
        index  
    }
    println(shuffledSongList[index].name)
}
  • Related