Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

kotlin

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?

like image 780
Leonardo Avatar asked Jun 24 '18 13:06

Leonardo


People also ask

How do I use contains in a list 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.") } }


1 Answers

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 } 
like image 170
zsmb13 Avatar answered Sep 18 '22 15:09

zsmb13