Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

lastornull
arraydeque
kotlin
communitycreator

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

Programming Bytes

Overview

The lastOrNull() method can be used to get the last element of the ArrayDeque. If the ArrayDeque is empty, then null is returned.

Syntax

fun lastOrNull(): E?

Parameter

This method does not take any argument.

Return value

Returns the last element if the ArrayDeque is not empty. Otherwise, null is returned.

Example

The example below demonstrates how to use the lastOrNull() method.

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

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

    // get the last element of deque
    lastEle = deque.lastOrNull();
    println("The last element is $lastEle");

}
Using the lasOrNull method

Explanation

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

Line 7: We use the lastOrNull method to get the last element of the deque. In this case, the deque is empty, so null is returned.

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

Line 18: We use the lastOrNull method to get the deque’s last element(4). The deque is not empty, so the last element of the deque is returned.

RELATED TAGS

lastornull
arraydeque
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring