Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

arraydeque
firstornull
kotlin
communitycreator

How to use the firstOrNull() method of ArrayDeque in Kotlin

Programming Bytes

Overview

In Kotlin, the firstOrNull() method is used to get the first element of ArrayDeque.

Syntax

fun firstOrNull(): E?

Parameter

This method doesn’t take any argument.

Return value

This method returns the first element if the ArrayDeque is not empty. Otherwise, it returns null.

Example

fun main() {
    // create a new empty ArrayDeque which can have int elements
    var deque = ArrayDeque<Int>()

    println("The Arraydeque is $deque")
    // get the first element of deque
    var firstEle = deque.firstOrNull();
    println("The First element is $firstEle");
    
    // add four elements to deque
    deque.add(1)
    deque.add(2)
    deque.add(3)
    deque.add(4)
    println("\nThe Arraydeque is $deque")

    // get the first element of deque
    firstEle = deque.firstOrNull();
    println("The First element is $firstEle");
}
Using the firstOrNull method

Explanation

  • Line 3: We create a new ArrayDeque with the name deque. It contains no element [].

  • Line 7: We use the firstOrNull method to get the first element of deque. In our case, the array is empty, so it returns null.

  • Lines 11–14: We use the add method to add four elements to deque. Now, deque has [1,2,3,4].

  • Line 18: We use the firstOrNull method to get the deque’s first element, 1. This array is not empty, so the first element of the deque is returned.

RELATED TAGS

arraydeque
firstornull
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring