Skip to main content

How to check if a HashSet is a subset of another HashSet in Kotlin

How to check if a HashSet is a subset of another HashSet in Kotlin.

Here's a step-by-step tutorial on how to check if a HashSet is a subset of another HashSet in Kotlin.

Step 1: Create two HashSets

First, we need to create two HashSets that we want to compare. Let's call them set1 and set2. You can initialize them with some initial values or leave them empty for now.

val set1 = HashSet<Int>()
val set2 = HashSet<Int>()

Step 2: Add elements to the HashSets

Next, let's add some elements to both set1 and set2. You can use the add method to add elements to a HashSet.

set1.add(1)
set1.add(2)
set1.add(3)

set2.add(1)
set2.add(2)
set2.add(3)
set2.add(4)

In this example, set1 contains elements 1, 2, and 3, while set2 contains elements 1, 2, 3, and 4.

Step 3: Check if set2 is a subset of set1

To check if set2 is a subset of set1, we can use the containsAll function. This function returns true if all elements in set2 are present in set1, and false otherwise.

val isSubset = set1.containsAll(set2)

In this example, isSubset will be true since all elements in set2 (1, 2, and 3) are present in set1.

Step 4: Print the result

Finally, let's print the result to see if set2 is a subset of set1.

if (isSubset) {
println("set2 is a subset of set1")
} else {
println("set2 is not a subset of set1")
}

This will print "set2 is a subset of set1" in our example.

Alternate Step: Check if set2 is a proper subset of set1 If you want to check if set2 is a proper subset of set1 (i.e., set2 is a subset of set1 but not equal to set1), you can modify the condition as follows:

val isProperSubset = set1.containsAll(set2) && set2.size < set1.size

Here, isProperSubset will be true only if all elements in set2 are present in set1 and the size of set2 is less than the size of set1.

I hope this tutorial helps you understand how to check if a HashSet is a subset of another HashSet in Kotlin!