How to use the removeLastOrNull method of ArrayDeque in Kotlin
Overview
The removeLastOrNull method will remove and return the last element of the ArrayDeque.
If the deque is empty then a null will be returned.
Syntax
// remove last element
fun removeLastOrNull(): E
Argument
This method does not take any argument.
Return value
The removeLastOrNull method returns the last element, which is removed. If the deque is empty then null is returned.
Code
The code below demonstrates how to use the removeLastOrNull method of the ArrayDeque:
fun main() {// create a new deque which can have string elementsvar deque = ArrayDeque<String>();println("The deque is " + deque);println("deque.removeLastOrNull() :" + deque.removeLastOrNull());// add three elements to dequeudeque.add("one");deque.add("two");deque.add("three");println("\nThe deque is " + deque);// remove the last elementprintln("\ndeque.removeLastOrNull() :" + deque.removeLastOrNull());println("The deque is " + deque);}
Code explanation
In the above code, we see the following:
Line 3: We create an ArrayDeque with the name deque.
Line 5: We use the removeLastOrNull method to remove and return the last element of the deque. In our case, the deque is empty so null is returned.
Lines 8–10: We use the add method to add three elements to the deque. Now the deque is [one,two,three].
Line 15: We use the removeLastOrNull method to remove and return the last element of the deque. In our case, three is removed from the deque and returned. Now the deque is [one,two].