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

后端 未结 4 1259
迷失自我
迷失自我 2020-12-31 01:58

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

相关标签:
4条回答
  • 2020-12-31 02:43

    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)
        }
    
    0 讨论(0)
  • 2020-12-31 02:51

    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 }
    
    0 讨论(0)
  • 2020-12-31 02:57

    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
    }
    
    0 讨论(0)
  • 2020-12-31 02:59

    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 }
    
    0 讨论(0)
提交回复
热议问题