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 elementsvar set: HashSet<Int> = hashSetOf<Int>()// Adding four entriesset.add(1)set.add(2)set.add(3)set.add(4)println("\nThe set is : $set")// Checking if the set contains the element 1println("\nset.contains(1) :" + set.contains(1));// Checking if the set contains the element 5println("\nset.contains(5) :" + set.contains(5));}
Explanation
-
Line 3: We create a new HashSet object named
set. We use thehashSetOf()method to create an empty HashSet. -
Lines 6–9: We add four new elements
1,2,3, and4tosetusing theadd()method. -
Line 14: We use the
containsmethod to check ifsetcontains the element1. The element1is present inset, so the method returnstrue. -
Line 17: We use the
containsmethod to check ifsetcontains the element5. The element5is not present inset, so the method returnsfalse.