Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

lastindexof
arraydeque
kotlin
communitycreator

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

Programming Bytes

Overview

The lastIndexOf() method will return the index of the last occurrence of the specified element in the ArrayDeque object.

Syntax

fun lastIndexOf(element: E): Int

Parameter

This method takes the parameter element, which represents the element to be searched in the deque.

Return value

This method returns the last index at which the specified element is present in the deque.

If the element is not present in the deque, then -1 is returned.

Code

The method below demonstrates how to use the lastIndexOf() method.

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

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

  // get lastIndexOf "one"
  println("\ndeque.lastIndexOf('one') : " + deque.lastIndexOf("one"));
  
  // get lastIndexOf "five"
  println("\ndeque.lastIndexOf('five') : " + deque.lastIndexOf("five"));
  
}
Using the lastIndexOf method

Explanation

In the code above,

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

  • Lines 6–9: We use the add method to add four elements to the deque. Now the deque is {one,one,two,three}.

  • Line 14: We use the lastIndexOf method of the deque object to get the index of the last occurrence of the element “one”. The element “one” is present at two indices: 0 and 1. We get 1 as a result since that is the last occurrence.

  • Line 17: We use the lastIndexOf method of the deque object to get the index of the last occurrence of the element “five”. The element “five” is not present so -1 is returned.

RELATED TAGS

lastindexof
arraydeque
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring