Collections Part 5 : Retrieve Single Item from Collection

Collections Part 5 : Retrieve Single Item from Collection

In this article , lets discuss about Kotlin Collections operation - retrieve single item from Collection using functions like elementAt() , first() , last() , random() , firstNotNullOf() and contains()


Foundation

  • List is an ordered collection which means every item in has its position that you are referring

  • Set is an unordered collection which stores element in certain order based on set implementation which can be LinkedHasSet , SortedSet , etc . So results are predictable based on the set implementation used

Position

elementAt()

  • retrieving item at specific position in given collection

  • called with Int argument

  • returns the collection item at given position

useful for collections that don't provide indexed access

In case of List , it has indexed access operator get() / []

first() - returns first collection item

last() - returns last collection item

elementAtOrNull() - returns null when the given parameter position is out of bounds for collection

elementAtOrElse()

  • takes lambda function that maps Int argument

  • returns one of the following

    1.returns elementAt() if the position passed is valid

    2.returns lambda function result if position is out of bounds

    val names = linkedSetOf("Sam", "Dev", "David", "Katherine", "Anne", "Chris")
    println(names.elementAt(1))
    // output : Dev

    println(names.first())
    // output : Sam
    println(names.last())
    // output : Chris

    println(names.elementAtOrNull(7))
    // output : null

    val result = names.elementAtOrElse(4) { index ->
        "The value at $index is invalid"
    }
    println(result)
    // output : Anne

Condition

first() with predicate - returns the first item matching the predicate in given collection

last() with predicate - returns the last item matching the predicate in given collection

if no items are matching the predicate , then both first() and last() throw exceptions

in those exception cases , we can use firstOrNull() and lastOrNull() which returns null if predicate is not matching with any items in given collection

find() can be used instead of firstOrNull()

findLast() can be used instead of lastOrNull()

 val names = linkedSetOf("Sam", "Dev", "David", "Katherine", "Anne", "Chris")

    println(names.first {
        it.length > 5
    })
    // output : Katherine

    println(names.last{
        it.endsWith("id")
    })
    // output : David

    println(names.firstOrNull{
        it.contains("Ae")
    })
    // output : null

    println(names.lastOrNull(){
        it.length>15
    })
    // output : null

    println(names.find {
        it.length > 6
    })
    // output : Katherine

    println(names.findLast {
        it.endsWith("is")
    })
    // output : Chris

Selection

firstNotNullOf()

  • maps the given collection with selector function

  • returns the first non null value of mapped collection

firstNotNullOfOrNull()

  • firstNotNullOf() throws NoSuchElementException if the result is null
    val names = linkedSetOf("Sam", "Dev", "David", "Katherine", "Anne", "Chris")

    val resultOne = names.firstNotNullOf { item ->
        item.length.takeIf { it > 6 }
    }
    println(resultOne)
    // output : 9

    val resultTwo = names.firstNotNullOfOrNull { item ->
        item.length.takeIf { it > 10 }
    }
    println(resultTwo)
    // output : null

Random

random() - gets a random item in collection

randomOrNull() - returns null if the given collection is empty

val names = linkedSetOf("Sam", "Dev", "David", "Katherine", "Anne", "Chris")

    println(names.random())

    val empty = linkedSetOf<String>()
    // println(empty.random())
    // output = Exception in thread 
    // "main" java.util.NoSuchElementException:
    //  Collection is empty.

    println(empty.randomOrNull())
    // output : null

Contains

contains()

  • checks if the item is in collection

  • returns true if the item matches the function argument

  • use in keyword for operator form of contains()

containsAll()

  • check multiple items together in given collection

isEmpty() / isNotEmpty()

  • to check if the collection contains any element
val names = linkedSetOf("Sam", "Dev", "David", "Katherine", "Anne", "Chris")

    println(names.contains("Sam"))
    // output : true

    println("Anne" in names)
    // output : true

    println(names.containsAll(listOf("David", "Bob")))
    // output : false
    println(names.containsAll(listOf("David", "Chris")))
    // output : true

    val numbers = listOf(1, 2, 3, 4, 5, 6)
    println(numbers.isEmpty())
    // output : false
    println(numbers.isNotEmpty())
    // output : true

    val emptyList = emptyList<String>()
    println(emptyList.isEmpty())
    // output : true
    println(emptyList.isNotEmpty())
    // output : false

Please leave your comments to improve.

Happy and Enjoy coding