Kotlin how to return a SINGLE object from a list t

2019-03-03 17:40发布

问题:

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?

回答1:

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 }


回答2:

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
}