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

后端 未结 4 1281
迷失自我
迷失自我 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:51

    You can do this with find, which gives you the first element of a list that matches a given predicate (or null, if none matched):

    val user: User? = myList.find { it.userId == id }
    

    Or if you really do need the last element that matches the predicate, as your Java example code does, you can use last:

    val user: User? = myList.last { it.userId == id }
    

提交回复
热议问题