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 somet
You can use this extension function also which return pair Pair(Boolean,T)
e.g
val id=2
val item= myList.customContains{it-> it.userId ==id}
if(item.first){
item.second //your object
// your code here
}else{
// if item no present
}
fun <E> List<E>.customContains(function: (currentItem: E) -> Boolean): Pair<Boolean, E?> {
for (current in 0 until this.size) {
if (function(this[current])) {
return Pair(true, this[current])
}
}
return Pair(false, 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 }
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 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
}
Simplify
val user: User = myList.single { it.userId == id }
or if may list not have your filter
val user: User? = myList.singleOrNull{ it.userId == id }