Kotlin how to return a SINGLE object from a list that contains a specific id?

后端 未结 4 1277
迷失自我
迷失自我 2020-12-31 01:58

Good day, i\'m stuck figuring out how to get a single object from a list, i did google but all the topics show how to return a List with sorted objects or somet

4条回答
  •  鱼传尺愫
    2020-12-31 02:57

    If you don't want to deal with null objects, try this:

    val index = myList.indexOfFirst { it.userId == id } // -1 if not found
    if (index >= 0) {  
        val user = myList[index]
        // do something with user
    }
    

提交回复
热议问题