问题描述
美好的一天,我一直在努力弄清楚如何从列表中获取单个对象,我做了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?
推荐答案
您可以使用 find
,它为您提供了与给定谓词(或null
,如果没有匹配)匹配的列表的第一个元素:
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示例代码一样),则可以使用 last
:
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的列表中返回单个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!