Table of contents
1.
Introduction
2.
Kotlin Set Interface
2.1.
Functions of Set Interface
3.
Kotlin MutableSet Interface
3.1.
Functions of MutableSet Interface
4.
Kotlin HashSet Class
4.1.
Functions of HashSet Class
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Sets

Author Rahul Sain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Kotlin Set Interface is a collection of components and can be organized in any order. The Set interface does not allow for duplicate elements. This interface is immutable, and its methods enable the set's read-only capabilities.

In this article, we will learn about Kotlin Sets and the need to use them. But before jumping into this, we would strongly recommend learning about Kotlin Arrays. We will learn how Sets are different from Arrays.

Kotlin makes a distinction between read-only and mutable sets. Read-only sets are produced with setOf(), and mutable sets are created with mutableSetOf().

Let’s move forward to understand this better with examples and uses.

Kotlin Set Interface

Set Interface employs the setOf() function to generate a list of set interface objects containing a list of elements.

Code:

fun main() {
   //implicit, non generic definition, non duplicate items
   val nonDuplicateSet = setOf(3, 2, '3', 4.0F, 5L, 3.0,"string",false,"3")
   //explicit, generic definition, duplicate items
   val duplicateSet: Set<Any> = setOf(3, 2, '3', '3', 4.0F, 5L, 3.0,"string",false,"3", 3.0)
   println("Printing nonDuplicateSet which have $nonDuplicateSet")
   println("Printing duplicateSet which have $duplicateSet")
}

Output:

Printing nonDuplicateSet which have [3, 2, 3, 4.0, 5, 3.0, string, false, 3]
Printing duplicateSet which have [3, 2, 3, 4.0, 5, 3.0, string, false, 3]

In above example, we have created two sets, one containing unique items and the second containing duplicate items using setOf(). Here a read-only set will be made, which is immutable.

Immutable means that their value can't be changed once defined. To make a mutable set, we will use mutableSetOf(), discussed later.

We can provide any value to the set, and it will implicitly typecast it to Any. We have declared duplicateSet variable explicitly to Any type.

Here, it is good to note that the output is the same in both cases, and it doesn't store duplicate items.

Now, we will see the functions of Set Interface.

Functions of Set Interface

We have a variety of functions that set provides to us. We will discuss some of them in the below example.

Code:

fun main() {
    val nonDuplicateSet = setOf(1,2,3,4,5,6,7,8,9,10)
    println(nonDuplicateSet.contains(11))
    println(nonDuplicateSet.containsAll(listOf(1,2,3)))
    println(nonDuplicateSet.drop(5))
    println(nonDuplicateSet.isEmpty())
    println(nonDuplicateSet.isNotEmpty())
 }

Output:

false
true
[6, 7, 8, 9, 10]
false
true

We have used contains(), which will return a boolean depending on the element passed as the argument. containsAll() also gives boolean value, but we supply a list. If you want to know more about lists, you can head over to this article.

drop(n) will return a list containing all elements except the first n elements in the given set.

Lastly, isEmpty() and isNotEmpty() returns boolean value depending on if the list is empty or not.

Kotlin MutableSet Interface

The MutableSet interface represents a generic unsorted collection of elements. The MutableSet interface does not support duplicate elements. Because this interface is changeable, its methods provide read-write functionality and the addition and removal of items.

MutableSet Interface utilizes the mutableSetOf() function to construct a list of set interface objects containing elements.

Code:

fun main() {
    val mutableSet = mutableSetOf<Int>(1,2,3,4,5,6,7,8,9,10)
    var sum = 0
    for(index in 0 until mutableSet.size){
        val currentItem = mutableSet.elementAt(index)
        sum += currentItem
    }
    println(sum)
 }

Output:

55

We are using mutableSetOf() instead of setOf() so that we can use add() and remove() functions on sets. We are explicitly defining the mutable set of Integer type.

We are using a for loop to iterate through each set item. Note If you want to know how this for loops works, please go to this article.

size() will return the total number of items in this set. The currentItem variable contains the current element of the present iteration of our loop. The elementAt() will return an element situated at the provided index. Finally, we add this item to our sum variable and print it.

Functions of MutableSet Interface

MutableSet contains all the functions of Set Interface which some additional functions like addAll() or removeAll().

Code:

fun main() {
    val mutableSet = mutableSetOf<Int>(1,2,3,4,5,6,7,8,9,10)
    val tempSet = mutableSetOf<Int>()
    tempSet.addAll(mutableSet) // adding mutableSet content to tempSet
    for(item in mutableSet){
        if(item % 2 == 0){
            // adding even number to tempSet
            tempSet.add(item)
        } else {
            // removing odd number from tempSet
            tempSet.remove(item)
        }
    }
    println(tempSet) // only contains non duplicate elements
    println(tempSet.indexOf(8)) // return the current index of element 8
    tempSet.removeAll(setOf(2,3,5,7,9)) // remove prime numbers from tempSet
    println(tempSet.any()) // if set contains at least one element
    println(tempSet) // content after the remove operation
    tempSet.clear()
    println("does tempSet contain any element ${tempSet.any()}, content of tempSet is $tempSet") // content after the clear operation
    println("original content of tempSet was $mutableSet")
 }

Output:

[2, 4, 6, 8, 10]
3
true
[4, 6, 8, 10]
does tempSet contain any element false, content of tempSet is []
original content of tempSet was [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We have created an empty set in tempSet variable. By using addAll(), we added the contents of mutableSet to tempSet, and it returns a boolean depending upon the success of the insert operation.

We are using a for each loop to iterate over every element. If the current element is even, then we are adding this element to tempSet else, we are removing the element from tempSet.

indexOf() returns the index of supplied element.If the supplied element is not found then this function will return -1.

Like addAll()removeAll() removes the List supplied to it from the tempSet and returned a boolean depending upon the success of the remove operation. clear() works the same way, but it removes all the elements from the tempSet. Finally, any() will check if the tempSet contains any element and return a boolean.

Kotlin HashSet Class

HashSet is a collection class that extends AbstractMutableSet and implements the Set interface, which uses a hashing mechanism to store elements. It supports both read and write operations. It does not handle duplicate values and does not assure element order sequencing.

Code:

fun main() {
    val hashSet = HashSet<Int>(5)
    val tempSet: HashSet<String> = hashSetOf()
 
    for (i in 0 until 5){
        hashSet.add(i)
    }
 
    for(index in 0 until hashSet.size){
        val current = hashSet.elementAt(index)
        tempSet.add("$current'")
    }
    println(hashSet) // Integer hashSet
    println(tempSet) // String tempSet
 }

Output:

[0, 1, 2, 3, 4]
[4', 3', 2', 1', 0']

hashSet variable has been defined by supplying its capacity during compile time. Variable tempSet has been initialized with no value.

We are iterating over each element to add every element from hashSet to tempSet. And finally, we are printing both variables.

Functions of HashSet Class

As HashSet implements the Set interface, it covers all the significant functions of the set. The above functions and their example can also be applied to HashSet. 

We can use add(), contains(), isEmpty(), remove(), clear() similarly in HashSet.

FAQs

  1. Is Set a list?
    A list is an ordered list of elements, whereas a set is an unordered list.
     
  2. Which is better, List or Set?
    Set is your best bet if you only need unique values, but List is the ideal option if elements keep the insertion order regardless of duplication.
     
  3. What is the difference between HashSet and HashMap?
    Because HashSet does not allow duplicate items, you cannot store identical values in it. Also, It accepts a single null value. Whereas, HashMap does not allow duplicate keys but does allow similar values. It allows for a single null key and unlimited null values.

Key Takeaways

Cheers if you reached here!! 

The purpose of this article was to introduce you to the Kotlin Sets, the basic syntax of implementing this, and understand the basic core concept about Sets, MutableSet, HashSet in Android Development.

If you want to learn more about Lamdas Expression in Kotlin, you can jump to this article which covers them in great detail.

Check out this problem - Duplicate Subtree In Binary Tree

However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. Till then, Happy Learning!

Live masterclass