MutableSetOf Kotlin

Learn via video courses
Topics Covered

Overview

Kotlin programming offers a powerful feature called the mutableSetOf interface that is used to manage collections. The mutableSetOf interface provides a powerful way to work with sets, allowing developers to add, remove, and modify elements efficiently. In this article, we will explore the fundamentals of mutableSetOf in Kotlin, including its syntax, functions, and usage through examples. We will also cover its advantages and disadvantages to help you make informed decisions while developing your Kotlin projects.

Syntax

The syntax for creating a MutableSet using mutableSetOf() is as follows:

KeywordDescription
funKeyword used to define a function in Kotlin. In the above syntax, we are defining a function named mutableSetOf.
<T>This represents a generic type parameter declaration. This means that mutableSetOf can work with elements of any data type, and the type is determined at the time of the function call.
mutableSetOfIt is the name of the function. Function names are typically descriptive to indicate their functionality.
varang elements: TThis part of the syntax defines a vararg parameter named elements. The vararg keyword allows you to pass a variable number of elements of type T to the function.
MutableSet<T>This is the return type of the function. It specifies that mutableSetOf will return a mutable set containing elements of type T.

Functions of MutableSetOf Interface

Kotlin provides several functions to perform on mutable sets. Some of them are discussed below:

FunctionDescription
add(element: E)Adds the given element to the collection.
addAll(elements: Collection<E>)Adds all the elements from the defined collection to the given collection.
clear()Removes all elements from the collection.
iterator()Returns an iterator that can be used to traverse the elements in the collection.
remove(element: E)Removes one element from the collection if it is present in the collection.
removeAll(elements: Collection<E>)Removes all elements from the collection that are also present in the specified collection.
retainAll(elements: Collection<E>)Retains only those elements in the collection that are present in the specified collection.
contains(element: E)Checks for the presence of an element in the specified collection.
containsAll(elements: Collection<E>)Checks for the presence of all the elements in the specified collection.
isEmpty()Checks if the set is empty or not and returns true if the collection contains no elements.
any()Checks if the set contains at least one element or not and returns true if at least one element matches the given predicate.
distinct()Returns a list containing only distinct elements from the specified collection.
drop(n: Int)Returns a list containing all elements except the first n elements.
elementAt(index: Int)Returns an element at the given index or throws an IndexOutOfBoundsException if the index is out of the bounds of the collection.
elementAtOrElse(index: Int, defaultValue: (Int) -> T)Returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of the collection.
max()Returns the largest element present in the collection or null if the collection is empty.
min()Returns the smallest element present in the collection or null if the collection is empty.
reversed()Returns a list with elements in reversed order.

Examples of MutableSetOf Interface

1. Creating a Mutable Set

Code:

Output:

Explanation:

In the above example, we've declared mutableSetA and mutableSetB using the mutableSetOf() function. mutablesetA is a set of integers, and mutablesetB is a set of strings. As we know the mutableSetOf function automatically eliminates duplicates, so even though the integer 3 is added twice to mutablesetA, it will only appear once in the output. However mutablesetB will be printed as it is since it contains all the unique elements.

2. Adding and Removing Elements in a Set

Code:

Output:

Explanation:

In the above example, we've declared a mutable set of colors with elements Black, Blue, and White. The code prints out the elements of the set using println. We added Yellow and Green to the set using the add() method and then printed out the updated set. We removed Yellow from the set using the remove() method and printed out the modified set again. Finally, the += operator and listOf function are used to add Orange to the set, followed by another printout of the updated colors set.

3. Set Indexing

Code:

Output:

Explanation:

In the above example, we've declared a mutable set called mutablesetA containing both integers and strings. Then we used the first() & last() functions to print out the first & last items of the set. Next, we used the indexOf() function to get the location of the 85 element. Finally, we removed the first four elements from the set using the drop() function and printed the resulting set without those elements.

4. Traversal in a Mutable Set

Code:

Output:

Explanation:

In the above example, we've declared a mutable set named listOfCountries. This set contains five strings that represent the names of different countries. The code then uses a for loop to go through each element of the set and print out the current element for each iteration. It prints each country name from the set one by one, achieving a traversal of the listOfCountries set.

5. Using add() and addAll() Functions

Code:

Output:

Explanation:

In the above example, we’ve declared two mutable sets: workDays, which initially holds the weekdays, and weekEnd, which contains the weekend days. We first displayed the workDays set, showing the weekdays. Then, we added Friday to the workDays set using the add() function and printed it again. Finally, we used the addAll() function to merge the weekEnd set (comprising of Saturday and Sunday) into the workDays set. The updated workDays set is then printed which includes all days.

6. Using remove() and removeAll() Functions

Code:

Output:

Explanation:

In the above example, we’ve declared two mutable sets: workDays, which initially holds the weekdays, and weekEnd, which contains the weekend days. We first displayed the “workDays” set, showing the weekdays. Then, we removed Friday from the workDays set using the remove() function and printed it again. Finally, we used the removeAll() function to remove the weekEnd set (comprising of Saturday and Sunday) from the workDays set. The updated workDays set is then printed.

7. Using contains() and containsAll() Functions

Code:

Output:

Explanation:

In the above example, we've declared a mutable set of fruits containing both integers and strings. After that, we've declared two variables setA and num to check whether the set contains the elements Kiwi and 55 or not. This is achieved using the contains() function. Lastly, it searches if all elements from the setOf(11, 31, “Orange”) exist in the fruits set and prints the results.

8. Using isEmpty() and any() Functions

Code:

Output:

Explanation:

In the above example, we’ve declared two mutable sets: workDays, which initially holds the weekdays, and weekEnd, which contains the weekend days. Then, we used the isEmpty() and any() functions inside the conditional statements to check if the sets were empty or not.

Advantages and Disadvantages of

Advantages:

  1. Efficient Element Access:
    Fast, direct access due to prohibition of duplicates.
  2. Dynamic Data Handling:
    Facilitates alteration of mutable objects, crucial for dynamic data.
  3. Built-in Functions:
    Offers efficient built-in operations for set management, saving coding effort.
  4. Constant Time Complexity:
    Provides O(1) time complexity for basic operations, ensuring consistent performance regardless of set size.

Disadvantages:

  1. Absence of Indexing:
    Lacks support for indexing, complicating element retrieval by position.
  2. Performance Impact:
    Slight performance dip during iteration compared to ArrayList due to hash table usage.
  3. Risk of Modifications:
    Potential for unintended set alterations; requires careful encapsulation to prevent unexpected behavior.

Conclusion

  1. A set is a collection that does not allow duplicate elements, ensuring each element is unique. MutableSetOf inherits from the Set interface, maintaining this uniqueness while providing methods for adding, removing, and updating elements.
  2. MutableSetOf is effective for managing dynamic data, and adapting to changing requirements in real-time applications.
  3. It doesn't guarantee element order; consider ArrayList for specific sequencing needs during iteration.
  4. Encapsulate mutableSetOf data to prevent unintended modifications, ensuring controlled changes based on program requirements.