What is the contains() method in Kotlin?

Overview

In Kotlin, the contains method is used to check if the ArrayDeque contains a specific value or not.

Syntax

fun contains(element: E): Boolean

Parameter value

This method takes the argument, element, which represents the value we want to find.

Return value

This method returns True if the passed value is equal to any of the values present in the ArrayDeque.

Checking the "ArrayDeque" with the "contains()" method

Code example

The code given below demonstrates how we can check if the ArrayDeque contains a specific value:

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("two");
deque.add("three");
println("The deque is " + deque);
// check if the deque contains the element one
println("\ndeque.contains('one'): " + deque.contains("one"));
// check if the deque contains the element five
println("\ndeque.contains('five'): " + deque.contains("five"));
}

Code explanation

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

  • Lines 6–8: We use the add method to add three elements to the deque. Now, the deque is [one, two, three].

  • Line 12: We use the contains method to check if the deque contains the element one. The element one is present in the deque, so true is returned.

  • Line 15: We use the contains method to check if the deque contains the element five. The element five is not present in the deque, so false is returned.

Free Resources