Kotlin如何从包含特定ID的列表中返回单个对象? [英] Kotlin how to return a SINGLE object from a list that contains a specific id?

查看:407
本文介绍了Kotlin如何从包含特定ID的列表中返回单个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,我一直在努力弄清楚如何从列表中获取单个对象,我做了google,但是所有主题都展示了如何返回带有已排序对象或类似对象的List.

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.

我有一个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
    }
}

在Java中,我会写类似的东西

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;
    }

我如何在Kotlin中获得相同的结果?

How can i achieve the same result in kotlin?

推荐答案

您可以使用

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 }

或者,如果您确实确实需要与谓词匹配的最后一个元素(如Java示例代码一样),则可以使用

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 }

这篇关于Kotlin如何从包含特定ID的列表中返回单个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆