Set in Kotlin : Avoid Duplicates using mutableSetOf() Function

Home » Kotlin » Set in Kotlin : Avoid Duplicates using mutableSetOf() Function

A set is a collection without a defined order and does not allow duplicate elements. To create sets, you can use the functions setOf() and mutableSetOf(). Let’s explore the Set in Kotlin with fruitful examples.

What is a Set?

A Set is an unordered collection that does not support duplicate elements. Unlike lists or arrays, which maintain the order of elements, sets focus on uniqueness. This means that each element in a set is unique, and any attempt to add a duplicate element will be automatically ignored.

Sets offer a variety of useful operations and methods to manipulate and retrieve elements efficiently. Let’s explore some common operations performed on sets.

Create a set using mutableSetOf() function

fun main()
    val fruits = mutableSetOf("Apple", "Orange","Pine apple", "Apple")
    println(fruits) // it will avoid duplicated elements


[Apple, Orange, Pine apple]

Set in Kotlin : How can I remove duplicate integers?

    val id: MutableSet<Int> = mutableSetOf(34,7,888,6,7,77,77,7)


[34, 7, 888, 6, 77]

Using setOf() function for read-only Sets

 val colors = setOf<String>("Blue", "Green")
[Blue, Green]

Adding and Removing Elements

fun main()
val phones = mutableSetOf("iPhone", "Pixel")
phones.add("Galaxy") // adding a new phone



iPhone, Pixel, Galaxy

Adding multiple items :

 // add multiple phones
    phones.addAll(listOf("iPhone","Pixel", "Phone(2)", "Flip Z"))

[iPhone, Pixel, Galaxy, Phone(2), Flip Z]

How to iterate using for loop and forEach?

 for(phone in phones)
    phones.forEach { phone -> println(phone) }

Removing elements from a Set

 phones.removeAll(listOf("Galaxy", "Flip Z"))
Pixel, Galaxy, Phone(2), Flip Z
Pixel, Phone(2)

Checking for Element Existence:

You can check if an element exists in a set using the contains() function, which returns a Boolean value indicating the presence or absence of the element.

        println("The set contains Google Pixel Phone")
    } else {
        println("The set does not contain Google Pixel Phone")

Set Operations in Kotlin : Union and Intersection

Sets support various set operations such as union, intersection, and difference. These operations allow you to combine sets, find common elements, or obtain elements unique to each set.

  // Set operations
    val a = setOf(1,2,3)
    val b = setOf(2,3,4)
    val union = a.union(b) //Union of a and b
    val intersection = a.intersect(b) // Intersection of a and b
    val difference = a.subtract(b) 
1, 2, 3, 4
2, 3

Converting Mutable Sets to Immutable Sets in Kotlin

val ids = mutableSetOf(3,45,5,4) // mutable
val readOnlyIds = ids as Set<Int> // immutable
var readOnlyIDs = ids.toSet() // immutable 

If you have a mutable set and want to obtain a read-only view of it, Kotlin allows you to cast the mutable set to an immutable set using the as keyword or the toSet() function.

Sets in Kotlin provide a powerful tool for managing collections of unique elements. With their ability to efficiently handle uniqueness and support set operations, sets prove to be valuable in various programming scenarios.

Whether you’re working with data that requires distinct values or need to perform operations like union and intersection, sets offer a clean and concise solution.

You may also like...