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 something similar.
I have a User Class
class User() { var email: String = "" var firstname: String = "" var lastname: String = "" var password: String = "" var image: String = "" var userId: String = "" constructor(email:String, firstname: String, lastname: String, password: String, image: String, userId : String) : this() { this.email = email this.firstname = firstname this.lastname = lastname this.password = password this.image = image this.userId = userId } }
In java i would write something like
User getUserById(String id) { User user = null; for(int i = 0; i < myList.size;i++;) { if(id == myList.get(i).getUserId()) user = myList.get(i) } return user; }
How can i achieve the same result in kotlin?
Kotlin Program fun main(args: Array<String>) { val list = listOf("ab", "bc", "cd") val element = "bc" if (list. contains(element)) { print("Element: $element is present in the list: $list.") } else { print("Element: $element is not present in the list: $list.") } }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With