Kotlin LinkedHashSet Class

Introduction

In Kotlin, LinkedHashSet is a hash table and linked list implementation of the MutableSet interface. It maintains the insertion order of its elements, meaning the order in which elements are inserted is preserved. LinkedHashSet is part of the kotlin.collections package and is used for storing and managing unique elements with efficient access, insertion, and deletion operations while maintaining order.

Table of Contents

  1. What is LinkedHashSet?
  2. Creating a LinkedHashSet
  3. Common Operations
  4. Examples of LinkedHashSet
  5. Real-World Use Case
  6. Conclusion

1. What is LinkedHashSet?

LinkedHashSet in Kotlin is a dynamic collection that allows you to store, access, and modify unique elements efficiently while maintaining the order of insertion. It is part of the kotlin.collections package and implements the MutableSet interface.

2. Creating a LinkedHashSet

You can create a LinkedHashSet using the constructor or by initializing it with elements.

Example

val emptySet = LinkedHashSet<Int>() // Creates an empty LinkedHashSet
val setWithElements = linkedSetOf(1, 2, 3, 4) // Creates a LinkedHashSet with elements

3. Common Operations

LinkedHashSet supports various operations for adding, removing, and accessing elements.

Adding Elements

  • add(element: E): Adds an element to the set. If the element already exists, it does nothing and returns false.

Removing Elements

  • remove(element: E): Removes the specified element from the set.

Checking Elements

  • contains(element: E): Checks if the set contains the specified element.
  • isEmpty(): Checks if the set is empty.
  • isNotEmpty(): Checks if the set is not empty.

Accessing Elements

  • iterator(): Returns an iterator over the elements in the set.

Checking Size

  • size: Returns the number of elements in the set.

Clearing the Set

  • clear(): Removes all elements from the set.

4. Examples of LinkedHashSet

Example 1: Adding Elements

add(element: E)

This example demonstrates how to add elements to the set.

fun main() {
    val set = LinkedHashSet<Int>()
    set.add(1)
    set.add(2)
    set.add(3)
    println("Set after adding elements: $set") // Output: Set after adding elements: [1, 2, 3]
}

Output:

Set after adding elements: [1, 2, 3]

Example 2: Removing Elements

remove(element: E)

This example demonstrates how to remove an element from the set.

fun main() {
    val set = linkedSetOf(1, 2, 3, 4)
    set.remove(3)
    println("Set after removing '3': $set") // Output: Set after removing '3': [1, 2, 4]
}

Output:

Set after removing '3': [1, 2, 4]

Example 3: Checking Elements

contains(element: E)

This example demonstrates how to check if the set contains a specified element.

fun main() {
    val set = linkedSetOf("apple", "banana", "cherry")
    println("Set contains 'banana': ${set.contains("banana")}") // Output: Set contains 'banana': true
    println("Set contains 'grape': ${set.contains("grape")}") // Output: Set contains 'grape': false
}

Output:

Set contains 'banana': true
Set contains 'grape': false

Example 4: Checking Size and Emptiness

size, isEmpty(), and isNotEmpty()

This example demonstrates how to check the size of the set and if it is empty.

fun main() {
    val set = linkedSetOf(10, 20, 30)
    println("Size of set: ${set.size}") // Output: Size of set: 3
    println("Is set empty: ${set.isEmpty()}") // Output: Is set empty: false
    println("Is set not empty: ${set.isNotEmpty()}") // Output: Is set not empty: true
}

Output:

Size of set: 3
Is set empty: false
Is set not empty: true

Example 5: Iterating Over a Set

iterator()

This example demonstrates how to iterate over the elements in the set.

fun main() {
    val set = linkedSetOf('a', 'b', 'c', 'd')
    val iterator = set.iterator()
    while (iterator.hasNext()) {
        println(iterator.next())
    }
}

Output:

a
b
c
d

Explanation:
This example shows how to iterate over the elements in a set using an iterator.

Example 6: Clearing the Set

clear()

This example demonstrates how to remove all elements from the set.

fun main() {
    val set = linkedSetOf(100, 200, 300)
    set.clear()
    println("Set after clearing: $set") // Output: Set after clearing: []
}

Output:

Set after clearing: []

5. Real-World Use Case: Maintaining Insertion Order

LinkedHashSet can be used to maintain the order of elements based on their insertion order, which is useful for ordered data representation.

Example: Maintaining Insertion Order

fun main() {
    val set = LinkedHashSet<String>()
    set.add("first")
    set.add("second")
    set.add("third")

    println("LinkedHashSet in insertion order:")
    for (element in set) {
        println(element)
    }
}

Output:

LinkedHashSet in insertion order:
first
second
third

Explanation:
This example shows how LinkedHashSet maintains the insertion order of elements, which can be useful for ordered data representation.

Conclusion

LinkedHashSet in Kotlin is a versatile and efficient dynamic collection from the kotlin.collections package, ideal for scenarios requiring unique elements and maintenance of insertion order. Properly utilizing LinkedHashSet can greatly enhance the performance and flexibility of your applications.

Comments