Set is a generic unordered collection of elements that does not support duplicate elements. Null elements are also unique. A set contain only one null. Kotlin distinguishes between read-only and mutable sets.

Kotlin distinguishes between read-only and read & write sets. Kotlin supports two types of sets mutable and immutable.

1. Immutable set

Set is a generic unordered collection of elements that does not support duplicate elements. setOf() is used for immutable set. Immutable set support only read only functionality.

Example For Immutable set

fun main() {
    //read-only set is created with setOf() function.
    val numbers = setOf(10, 12, 22, 14, 18, 20)
    println(numbers)
}

Output ->
[10, 12, 22, 14, 18, 20]

1.1 Set indexing

Each element of a set has an index. Kotlin set indexes start from zero. The last element has lenght -1 index. 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.

// Set Indexing
fun main() {

    val players = setOf(
        "Kieron Pollard", "Trent Boult", "Surya Kumar Yadav", "Malinga", "Rohit"
    )

    // Returns the First value in the list
    val singlePlayer = players.elementAt(0)
    println(singlePlayer)

    // The indexOf() returns the index of the first players of the word in the set.
    val findPlayerIndex = players.indexOf("Trent Boult")
    println("The index of Trent Boult is $findPlayerIndex")

    println("First element of set players : " + players.first())
    println("Last element of set players : " + players.last())
}

Output ->
Kieron Pollard
The index of Trent Boult is 1
First element of set players : Kieron Pollard
Last element of set players : Rohit

1.2 Functions of set

In Kotlin,you have so many functions.

1. contain() and ContainAll()

The contains() function checks the given element is present in current set or not. If it is contains in the set, the set returns true else returns false. The containsAll() function checks all the elements of collection type are present in the current set or not. If the set contains all elements of collection type it returns true else false.

fun main() {
    // creating a set
    val firstSet: Set<Int> = setOf(10, 20, 30, 40, 50)
    val secondSet: Set<Int> = setOf(10, 20, 30)

    // contain() function
    println("Does set contain the element 40 : ${firstSet.contains(40)}")

    // containAll() Function
    println("Does set contain all elements of firstSet: ${firstSet.containsAll(secondSet)}")

    // isEmpty Function
    println("Is secondSet empty : ${firstSet.isEmpty()}")
}

Output ->
Does set contain the element 40 : true
Does set contain all elements of firstSet: true
Is secondSet empty : false

2. isEmpty()

The isEmpty() function checks the set is empty or not.If the set is empty is empty return ture else return false.

fun main() {
    //creating a set
    val numberSet: Set<Int> = setOf(10, 20, 30, 40, 50)
    //isEmpty Function
    println("Is numberSet empty : ${numberSet.isEmpty()}")
}

Output ->
Is myset is empty : false

3. count(), sum(), average()

count() function returns the number of elements in the set.
sum() function return the sum of elements in the set.
average() function return the average value of the elements in the set.

fun main() {
    val numberSet = setOf(2, 4, 6, 8, 10, 12)
    println(numberSet)
    // Returns the number of elements in the set.
    println(numberSet.count())
    // Return the sum of elements in the set.
    println(numberSet.sum())
    // Return the average value of the elements in the set.
    println(numberSet.average())
}

Output ->
[2, 4, 6, 8, 10, 12]
6
42
7.0

4. Sorting

The sets created with setOf() are read-only, the methods do not alter the set but return a new modified list.

  • sorted() method returns a list of all elements sorted according to their natural sort order.
  • sortedDescending() method returns a list of all elements sorted descending order.
  • reversed() method returns a list with elements in reversed order.
fun main() {
    val numberSet = setOf(2, 4, 6, 8, 10, 12)

    // Returns a list of all elements sorted according to their natural sort order.
    println(numberSet.sorted())

    // Returns a list of all elements sorted descending according to their natural sort order.
    println(numberSet.sortedDescending())

    // Returns a list with elements in reversed order.
    println(numberSet.reversed())
}

//Output ->
[2, 4, 6, 8, 10, 12]
[12, 10, 8, 6, 4, 2]
[12, 10, 8, 6, 4, 2]

5. Union

The union operation returns a set containing all elements from both collections.

fun main() {
    val numberSet = setOf(2, 4, 6, 8, 10, 12)
    println(numberSet)
    val integerSet = setOf(4, 8, 12, 16, 20)
    println(integerSet)
    
    // Returns a set containing all distinct elements from both collections.
    val unionSet = numberSet.union(integerSet)
    println("UnionSet : $unionSet")
}

Output ->
[2, 4, 6, 8, 10, 12]
[4, 8, 12, 16, 20]
UnionSet : [2, 4, 6, 8, 10, 12, 16, 20]

6. Set mapping

The mapping operation returns a modified list by applying a transform function on each element of the set.

fun main() {
    val numberSet = setOf(2, 4, 6, 8, 10, 12)
    println(numberSet)
    
    // Returns a modified list by applying a transform function on each element of the set.
    val mapSet = numberSet.map { e ->
        e * 2
    }
    println("mapSet: $mapSet")
}

Output ->
[2, 4, 6, 8, 10, 12]
mapSet: [4, 8, 12, 16, 20, 24]

7. groupBy

The groupBy() method groups elements of the original set by the condition, applied to each element. It returns a map where each group key is associated with a list of corresponding elements.

fun main() {
    val dataSet = setOf(2, 4, 5, 6, 7, 8, 9, 10)

    // GroupBy method
    val result = dataSet.groupBy {
        if (it % 2 == 0) {
            "even"
        } else {
            "odd"
        }
    }
    println(result)
}

Output ->
{even=[2, 4, 6, 8, 10], odd=[5, 7, 9]}

8. Filter

filter() returns the collection elements that match predicate.

fun main() {
    val nameSet = setOf("Bob", "Rohit", "Madhu", "Richa", "Jessy", "Rohitha")

    // Filter lambda function
    val filteredValues = nameSet.filter {
        it == "Rohit"
    }
    println(filteredValues)
}

Output ->
[Rohit]

2. Mutable set

Mutable set also unordered collection of elements that does not support duplicate elements.mutableSetOf() is used for mutable sets.Mutable set support both read write functionality.Mutable set allows you to add and remove elements in set.

Example :

fun main() {
    // Declaring a mutable set with different types
    val mySet: Set<Any> = mutableSetOf(1, "a", "Developers", 12.3)

    println("Display the values in set")

    // Print the elements in the set
    println(mySet)
}

Output ->
Display the values in set
[1, a, Developers, 12.3]

2.1 Adding and Removing elements in a set

using add() function you can elements add elements and using remove() function you can remove elements from mutable set another way to add elements is by using listOf() function.Let us see one program to understand add() and remove() functions.

fun main() {
    // Declaring a mutable set with all types
    val mutableSet = mutableSetOf(1, "a", "Developers", 12.3)

    // Using add() function you can add elements from mutable set.
    mutableSet.add(2)
    mutableSet.add(3)
    println(mutableSet)

    // Using remove() function you can remove elements from mutable set
    mutableSet.remove(12.3)
    println(mutableSet)

    // Using list of function to add elements to the mutable set.
    mutableSet += listOf(4, 5)
    println(mutableSet)
}

Output ->
[1, a, Developers, 12.3, 2, 3]
[1, a, Developers, 2, 3]
[1, a, Developers, 2, 3, 4, 5]

2.2 Indexing in mutable set

Each element of a set has an index. Kotlin set indexes start from zero. The last element has length -1 index. 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. Refer to heading 1.1 on set indexing example.

3. Project code and resources

That’s it! Thanks for reading the article, hope it was helpful !

Here We Go Again : (

if (article == helpful) {
    println("Like and subscribe to blog newsletter.")
} else {
    println("Let me know what i should blog on.")
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.