Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin hashSetOf()

In Kotlin, HashSet is a mutable collection that doesn't allow duplicate elements and doesn't guarantee the order of elements. The hashSetOf() function is a convenient way to create a HashSet. Here's a tutorial on how to use hashSetOf() in Kotlin:

1. Initializing a HashSet:

You can use the hashSetOf() function to initialize a HashSet:

val set1 = hashSetOf<Int>()      // Empty HashSet
val set2 = hashSetOf(1, 2, 3, 4) // HashSet with initial values

2. Adding Elements:

Although the initial values can be set using hashSetOf(), you can also add elements later:

val fruits = hashSetOf("Apple", "Banana")
fruits.add("Cherry")

3. Checking for an Element:

You can check whether an element exists in the set:

val hasApple = "Apple" in fruits  // true
val hasGrape = "Grape" in fruits  // false

4. Removing Elements:

fruits.remove("Apple")  // Removes the element "Apple" from the set

5. Iterating Through a HashSet:

for (fruit in fruits) {
    println(fruit)
}

6. Set Operations:

Kotlin provides various functions to perform set operations:

val setA = hashSetOf(1, 2, 3, 4)
val setB = hashSetOf(3, 4, 5, 6)

val union = setA.union(setB)           // Results in [1, 2, 3, 4, 5, 6]
val intersection = setA.intersect(setB) // Results in [3, 4]
val difference = setA.subtract(setB)   // Results in [1, 2]

7. Size and Other Properties:

val size = fruits.size       // Returns the number of elements
val isEmpty = fruits.isEmpty() // Checks if the set is empty

8. Clearing All Entries:

fruits.clear()  // Removes all elements from the set

9. Converting to Other Collections:

You can easily convert a HashSet to other collections, like lists:

val fruitList = fruits.toList()

10. Filtering:

You can use the filter function to get a new set that satisfies a particular condition:

val filteredSet = fruits.filter { it.startsWith('A') }.toHashSet()

Conclusion:

HashSet is a useful collection in Kotlin when you need a group of unique elements without any specific order. Using hashSetOf(), you can easily create and initialize a HashSet. Familiarity with HashSet and its operations can greatly assist in many programming scenarios where duplicates are unwanted.

  1. Creating a HashSet in Kotlin:

    • Initialize an empty HashSet.
    val hashSet = HashSet<String>()
    
  2. Initializing and declaring a HashSet using hashSetOf():

    • Initialize and declare a HashSet with values.
    val uniqueNumbers = hashSetOf(1, 2, 3, 4, 5)
    
  3. Adding and removing elements in a Kotlin HashSet:

    • Add and remove elements.
    uniqueNumbers.add(6)  // Adding
    uniqueNumbers.remove(3)  // Removing
    
  4. Accessing values in a HashSet in Kotlin:

    • Check if an element exists.
    val containsTwo = 2 in uniqueNumbers
    
  5. Iterating over a HashSet in Kotlin:

    • Iterate through elements.
    for (number in uniqueNumbers) {
        println(number)
    }
    
  6. Difference between hashSetOf() and mutableSetOf() in Kotlin:

    • Understand the difference between the two.
    val setA = hashSetOf(1, 2, 3)
    val setB = mutableSetOf(4, 5, 6)
    
  7. Default values for HashSet in Kotlin:

    • Provide default values when accessing non-existing elements.
    val defaultIfAbsent = uniqueNumbers.getOrElse(10) { 0 }
    
  8. Filtering and transforming values in a Kotlin HashSet:

    • Use filter and map to manipulate values.
    val evenNumbers = uniqueNumbers.filter { it % 2 == 0 }
    val squaredNumbers = uniqueNumbers.map { it * it }
    
  9. Checking if an element exists in a Kotlin HashSet:

    • Check for the existence of an element.
    val containsFour = uniqueNumbers.contains(4)
    
  10. Converting other collections to a HashSet in Kotlin:

    • Convert other collections to HashSet.
    val list = listOf(1, 2, 3, 4, 5)
    val setFromList = list.toHashSet()
    
  11. Handling null values in a Kotlin HashSet:

    • Use nullable types to handle potential null values.
    val nullableValue: Int? = uniqueNumbers.find { it == 3 }
    
  12. Using hashSetOf() with data classes in Kotlin:

    • Use HashSet with data classes.
    data class Person(val name: String, val age: Int)
    
    val peopleSet = hashSetOf(
        Person("Alice", 25),
        Person("Bob", 30)
    )