Kotlin mutableSetOf() method
Last Updated :
25 May, 2025
In Kotlin, a Set is a generic unordered collection of elements that does not allow duplicate elements. Kotlin provides two main types of sets:
- Immutable Set: Created using setOf() – supports only read-only operations.
- Mutable Set: Created using mutableSetOf() – supports both read and write operations.
In this article, we are going to learn about mutable set, i.e., mutableSetOf().
To learn about Immutable set, refer to Kotlin Set : setOf()
Syntax:
fun <T> mutableSetOf(vararg elements: T): MutableSet<T>
Description:
The mutableSetOf() function returns a mutable set containing the specified elements. The elements can be read, added, or removed. The order of elements is preserved during iteration.
Example of mutableSetOf() function :
Kotlin
fun main() {
//declaring a mutable set of integers
val mutableSetA = mutableSetOf<Int>( 1 , 2 , 3 , 4 , 3);
println(mutableSetA)
//declaring a mutable set of strings
val mutableSetB = mutableSetOf<String>("Geeks","for" , "geeks");
println(mutableSetB)
//declaring an empty mutable set of integers
val mutableSetC = mutableSetOf<Int>()
println(mutableSetC)
}
Output:
[1, 2, 3, 4]
[Geeks, for, geeks]
[]
Adding and removing elements in a set -
We can add elements in a mutable set using the add() function, and remove an elements using remove () function.
Example :
Kotlin
fun main() {
//declaring a mutable set of integers
val seta = mutableSetOf( 1 , 2 , 3 , 4 , 3);
println(seta);
//adding elements 6 & 7
seta.add(6);
seta.add(7);
println(seta);
//removing 3 from the set
seta.remove(3);
println(seta);
//another way to add elements is by using listOf() function
seta += listOf(8,9)
println(seta)
}
Output:
[1, 2, 3, 4]
[1, 2, 3, 4, 6, 7]
[1, 2, 4, 6, 7]
[1, 2, 4, 6, 7, 8, 9]
Accessing Elements by Index -
Though sets are unordered, Kotlin provides some functions for index-based access:
- elementAt(index)
- indexOf(element)
- lastIndexOf(element)
Example of using index –
Kotlin
fun main() {
val captains = mutableSetOf("Kohli","Smith","Root","Malinga","Rohit","Dhawan")
println("The element at index 2 is: "+captains.elementAt(2))
println("The index of element is: "+captains.indexOf("Smith"))
println("The last index of element is: "+captains.lastIndexOf("Rohit"))
}
Output:
The element at index 2 is: Root
The index of element is: 1
The last index of element is: 4
Accessing First and Last Elements –
We can get the first and element of a set using first() and last() functions.
Example –
Kotlin
fun main() {
val captains = mutableSetOf(1,2,3,4,"Kohli","Smith","Root","Malinga","Dhawan","Rohit")
println("The first element of the set is: "+captains.first())
println("The last element of the set is: "+captains.last())
}
Output:
The first element of the set is: 1
The last element of the set is: Dhawan
Traversing a Mutable Set -
We can iterate over a mutable set using a for loop:
Kotlin
fun main() {
//declaring a mutable set of integers
val seta = mutableSetOf( 1 , 2 , 3 , 4 , 3);
//traversal of seta using an iterator 'item'
for (item in seta) {
println( item )
}
}
Output:
1
2
3
4
Checking for Elements –
We can use contains() and containsAll() to verify presence of elements:
Example of using contains() and containsAll() function –
Kotlin
fun main(){
val captains = mutableSetOf(1,2,3,4,"Kohli","Smith", "Root","Malinga","Rohit","Dhawan")
var name = "Dhawan"
println("The set contains the element $name or not?" + " "+captains.contains(name))
var num = 5
println("The set contains the element $num or not?" + " "+captains.contains(num))
println("The set contains the given elements or not?" + " "+captains.containsAll(setOf(1,3,"Root")))
}
Output:
The set contains the element Dhawan or not? true
The set contains the element 5 or not? false
The set contains the given elements or not? true
Working with Empty Sets and isEmpty() -
fun <T> mutableSetOf(): mutableSet<T>
This syntax returns an empty set of specific type.
Example of using isEmpty() function -
Kotlin
fun main() {
//creating an empty set of strings
val seta = mutableSetOf<String>()
//creating an empty set of integers
val setb = mutableSetOf<Int>()
//checking if set is empty or not
println("seta.isEmpty() is ${seta.isEmpty()}")
// Since Empty sets are equal
//checking if two sets are equal or not
println("seta == setb is ${seta == setb}")
println(seta) //printing first set
}
Output :
seta.isEmpty() is true
seta == setb is true
[]
Full Example Demonstrating mutableSetOf() -
Kotlin
fun main() {
// Create a mutable set of fruits
val fruits = mutableSetOf("apple", "banana", "cherry")
// Add a new fruit to the set
fruits.add("orange")
println("Fruits after adding orange: $fruits")
// Remove a fruit from the set
fruits.remove("banana")
println("Fruits after removing banana: $fruits")
// Check if the set contains a particular fruit
val hasApple = fruits.contains("apple")
val hasMango = fruits.contains("mango")
println("Fruits contains apple: $hasApple")
println("Fruits contains mango: $hasMango")
// Iterate over the elements of the set
println("Fruits:")
for (fruit in fruits) {
println("- $fruit")
}
}
Output:
Fruits after adding orange: [apple, banana, cherry, orange]
Fruits after removing banana: [apple, cherry, orange]
Fruits contains apple: true
Fruits contains mango: false
Fruits:
- apple
- cherry
- orange
Advantages of mutableSetOf():
- It allows the programmer to create a set of mutable objects, which can be modified later as needed. This is particularly useful when dealing with dynamic data, where the size and content of the set can change at runtime.
- It provides efficient performance for adding, removing, and checking if an element is present in the set. The mutableSetOf() function internally uses a hash table to store the elements, which ensures that these operations are O(1) time complexity on average.
- It provides easy-to-use methods to modify the set, such as add(), remove(), and clear(), which make it simple to add or remove elements from the set as needed.
Disadvantages of mutableSetOf():
- The hash table used by the mutableSetOf() function can result in slightly slower performance than an ArrayList when iterating over the elements of the set. This is because the hash table does not maintain a particular order of the elements.
- Since mutableSetOf() creates a mutable set, there is a risk of unintentionally modifying the set from different parts of the code, which can result in unexpected behavior. This can be avoided by ensuring that the mutable set is properly encapsulated and accessed only through the appropriate methods.
Similar Reads
Kotlin mutableListOf()
In Kotlin, mutableListOf() method is used to instantiate MutableList Interface. MutableList class is used to create mutable lists in which the elements can be added or removed. The method mutableListOf() returns an instance of MutableList Interface and takes the array of a particular type or mixed (
3 min read
Kotlin mutableMapOf()
Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.For
4 min read
Kotlin list : listOf()
In Kotlin, listOf() is a function that is used to create an immutable list of elements. The listOf() function takes a variable number of arguments and returns a new list containing those arguments. Here's an example: Kotlin val numbers = listOf(1, 2, 3, 4, 5) In this example, we create a new list ca
8 min read
Kotlin Map : mapOf()
In Kotlin, a Map is a collection that stores data in key-value pairs. Each key in a map is unique, and the map holds only one value for each key. If a key is repeated, only the last value is retained.Kotlin distinguishes between:Immutable maps (mapOf()) - read-onlyMutable maps (mutableMapOf()) - rea
5 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. The declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type o
2 min read
Kotlin Reflection
Reflection is a set of language and library features that provides the feature of introspecting a given program at runtime. Kotlin reflection is used to utilize class and its members like properties, functions, constructors, etc. at runtime. Along with Java reflection API, Kotlin also provides its o
3 min read
Kotlin partition() Method with Examples
In this article, we are going to discuss how to split the original collection into pair of collections, because sometimes while coding, you wish that you could just split a list into sublists without going into the for and while loops. Kotlin provides you with a function just for this occasion. In t
4 min read
Overriding Rules in Kotlin
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. You decided your new class has to redefine one of the methods inherited
3 min read
Java HashMap putIfAbsent() Method
The putIfAbsent() method of the HashMap class in Java is used to insert a key-value pair into the map only if the key is not present in the map or is mapped to null. The existing value remains unchanged if the key is already associated with a value.Example 1: In this example, we will demonstrate the
3 min read
How to Add Element in an Immutable Seq in Scala?
In this article, we will learn how to add elements in immutable seq in Scala. immutable sequences, such as List, cannot have elements added to them directly because they are designed to be immutable. However, you can create a new sequence with an additional element by using methods like :+ (for appe
2 min read