Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

removefirstornull
arraydeque
kotlin
communitycreator

How to use the removeFirstOrNull method of ArrayDeque in Kotlin

Programming Bytes

Overview

The removeFirstOrNull method will remove and return the first element of the ArrayDeque.

If the deque is empty then a null will be returned.

Syntax

// remove first element
fun removeFirstOrNull(): E

Parameter

This method doesn’t take any argument.

Return value

The removeFirstOrNull method returns the first element which is removed. If the deque is empty then null is returned.

Example

The code below demonstrates how to use the removeFirstOrNull method of the ArrayDeque:

fun main() {
  // create a new deque which can have string elements
  var deque = ArrayDeque<String>();
  println("The deque is " + deque);
  println("deque.removeFirstOrNull() :" + deque.removeFirstOrNull());
  
  // add three elements to dequeu
  deque.add("one");
  deque.add("two");
  deque.add("three");

  println("\nThe deque is " + deque);

  // remove the first element 
  println("\ndeque.removeFirstOrNull() :" + deque.removeFirstOrNull());
  println("The deque is " + deque);
}
Using the `removeFirstOrNull` method

Explanation

  • Line 3: We create an ArrayDeque with the name deque.

  • Line 5: We use the removeFirstOrNull method to remove and return the first element of the deque. In our case, the deque is empty so null is returned.

  • Lines 8–10: We usd the add method to add three elements to the deque. Now the deque is {one,two,three}.

  • Line 15: We use the removeFirstOrNull method to remove and return the first element of the deque. In our case one is removed from the deque and returned. Now the deque is {two, three}.

RELATED TAGS

removefirstornull
arraydeque
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring