How to check if a HashSet contains an element in Kotlin

Overview

The contains method in Kotlin checks whether a HashSet contains a specific value.

Syntax

fun contains(element: E): Boolean

Parameters

  • element: This represents the value whose presence we want to check inside the HashSet.

Return value

This method returns true if the passed value is present inside the HashSet. It returns false if the value is not present inside the HashSet.

Example

The code snippet below demonstrates how to check for the existence of a value inside a HashSet using the contains method.

fun main() {
//Creating a new HashSet that can have integer types as elements
var set: HashSet<Int> = hashSetOf<Int>()
// Adding four entries
set.add(1)
set.add(2)
set.add(3)
set.add(4)
println("\nThe set is : $set")
// Checking if the set contains the element 1
println("\nset.contains(1) :" + set.contains(1));
// Checking if the set contains the element 5
println("\nset.contains(5) :" + set.contains(5));
}

Explanation

  • Line 3: We create a new HashSet object named set. We use the hashSetOf() method to create an empty HashSet.

  • Lines 6–9: We add four new elements 1, 2, 3, and 4 to set using the add() method.

  • Line 14: We use the contains method to check if set contains the element 1. The element 1 is present in set, so the method returns true.

  • Line 17: We use the contains method to check if set contains the element 5. The element 5 is not present in set, so the method returns false.

Free Resources