Kotlin mutableSetOf() method
Last Updated :
17 Mar, 2023
Kotlin Set interface is a generic unordered collection of elements and it does not contain duplicate elements. Kotlin supports two types of sets mutable and immutable.
setOf() is immutable means it supports only read-only functionalities and mutableSetOf() is mutable means it supports read and write both functionality.
Syntax:
fun <T> mutableSetOf( vararg elements: T): MutableSet<T>
Description:
- This function returns a set of given elements, which can be both read and written.
- The returned set preserves the element iteration order.
Kotlin program of mutableSetOf() function :
Kotlin
fun main(args: Array<String>)
{
val mutableSetA = mutableSetOf<Int>( 1 , 2 , 3 , 4 , 3);
println(mutableSetA)
val mutableSetB = mutableSetOf<String>("Geeks","for" , "geeks");
println(mutableSetB)
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(args: Array<String>)
{
val seta = mutableSetOf( 1 , 2 , 3 , 4 , 3);
println(seta);
seta.add(6);
seta.add(7);
println(seta);
seta.remove(3);
println(seta);
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]
Set Indexing â
Using index functions indexOf() , lastIndexOf() we can get the index of the specified element. And we can also find the elements at some specific index using elementAt() function.
Kotlin program of using index â
Kotlin
fun main(args: Array<String>) {
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
Set first and last element â
We can get the first and element of a set using first() and last() functions.
Kotlin program â
Kotlin
fun main(args: Array<String>){
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
Traversal in a mutableSet –
We can run a for loop with an iterator which traverse all the items in the set .
Kotlin
fun main(args: Array<String>)
{
val seta = mutableSetOf( 1 , 2 , 3 , 4 , 3);
for(item in seta)
println( item )
}
|
Output:
1
2
3
4
contains() and containsAll() functions â
Both the methods are used to check whether an element is present in the set or not?
Kotlin program of using contains() and containsAll() function â
Kotlin
fun main(args: Array<String>){
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
Checking equality of empty sets and use of isEmpty() functions –
fun <T> mutableSetOf(): mutableSet<T>
This syntax returns an empty set of specific type.
Kotlin program of using isEmpty() function –
Kotlin
fun main(args: Array<String>) {
val seta = mutableSetOf<String>()
val setb = mutableSetOf<Int>()
println("seta.isEmpty() is ${seta.isEmpty()}")
println("seta == setb is ${seta == setb}")
println(seta)
}
|
Output :
seta.isEmpty() is true
seta == setb is true
[]
Sure, here’s an example of using the mutableSetOf() function to create a set of fruits and then adding, removing, and iterating over the elements of the set:
Kotlin
fun main() {
val fruits = mutableSetOf("apple", "banana", "cherry")
fruits.add("orange")
println("Fruits after adding orange: $fruits")
fruits.remove("banana")
println("Fruits after removing banana: $fruits")
val hasApple = fruits.contains("apple")
val hasMango = fruits.contains("mango")
println("Fruits contains apple: $hasApple")
println("Fruits contains mango: $hasMango")
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
Rashi/Zodiac Chart: Know Your Rashi by Name and Date Of Birth
The Indian astrology system recognizes 12 Rashis or Zodiac Signs, each with distinct characteristics. The Moon sign, determined by the Moon's placement at birth, is crucial in Vedic Astrology. Understanding Zodiac Signs helps individuals discover their personality traits, compatibility, and what the
13 min read
100+ Happy Birthday Wishes: Sweet Quotes & Message ideas
Birthday is the most important day in anyone's life. So wishing your friends, relatives, or colleagues a Happy birthday will make the bond super strong. We have crafted the Top 100 Happy Birthday wishes that you can share on the eve with your friends, partner, or any colleague. Happy Birthday Wishes
14 min read
15 Best IPTV Service Providers Subscriptions (Top Picks)
Finding a reliable IPTV service provider can be challenging with so many options available. As streaming becomes the new standard for entertainment, IPTV services have gained huge popularity by offering a wide variety of TV channels, on-demand content, and international programmingâall through an in
14 min read
Best Free Movie Download Sites for 2024
Want to watch a movie whenever you want? Simply download it to your device and watch it later, even if you don't have an internet connection. This is called "streaming it locally." The best part about downloading a movie is that it's always ready for you, no matter where you are! Most legal movie do
9 min read
6 Best ChatGPT Plugin for Summarizing YouTube Videos Quickly
Presenting the best ChatGPT plugin for YouTube summary that will transform media consumption. Gathering important ideas from long YouTube videos in a world full of information can be intimidating. It reduces intricate information into a brief synopsis, enabling you to quickly assimilate the main poi
9 min read
ChatGPT Tips & Tricks: 5 Secret Tips That Can Boost Your ChatGPT Game to God Mode
Are you one of those folks who've tried using ChatGPT but ended up feeling a bit frustrated? Well, let us tell you, you're not alone in this sad situation. Whether you're a student or a tech whiz working in IT, ChatGPT has been a helpful companion for everyone! But the thing is, not everyone knows h
7 min read
IPTV España: Los 10 Mejores Proveedores de Listas IPTV en España
En España, IPTV se ha consolidado como la opción preferida de muchos usuarios en España. En 2025, encontrar los mejores proveedores de listas de IPTV se ha convertido en una tarea crucial para disfrutar de una experiencia televisiva excepcional. Este artÃculo explora el universo de IPTV España, desg
10 min read
How to Download and Install the Google Play Store
The Google Play Store is the heartbeat of your Android experienceâhome to millions of apps, games, and updates that keep your device functional, fun, and secure. But what if your phone or tablet doesnât have it pre-installed? In this step-by-step guide, youâll learn how to safely download and instal
6 min read
Free Reverse Phone Number Lookup Services and Sites: 10 Best Picks in 2025
Find all the latest list of Reverse Phone Number Lookup Services and Sites - Due to the rapid increase in numbers of spam calls and unknown numbers it has now become vital to use reverse phone number lookup services. Whether you're trying to identify an unknown caller or check the legality of a phon
12 min read
10 Most Beautiful Women in the World 2024
Most Beautiful Women in the World: "Beauty is the feeling that draws at your heart, creating a warm and joyful emotion." Everybody feels happy and warm by looking at beautiful things. Human beauty is the pleasing and attractive quality found in a person's appearance, reflecting a combination of phys
10 min read