Updated March 31, 2023
Introduction to Kotlin set
The kotlin set is one of the collection interfaces, and it is used to set the elements using the generic unordered collection of elements; it does not accept the duplicate elements, and the methods in this interface are support only the readable access the interface is the immutable nature mainly the setOf() method is used for to create the list of objects which contains a list of elements the kotlin set is not only in immutable it also supports mutable classes and methods like mutableSetOf() that means it supports both read and write functionality, so it returns a new read-only set of elements.
Syntax
In kotlin, language has many default keywords, variables, functions, and classes to implement the application like that kotlin set is the interface that can support both mutable and immutable classes and methods.
fun main(args:Array<String>)
{
val vars= setof(values)
loops for to iterate the values
---some logic codes---
}
The above code is the basic syntax for to utilising the set collection interface in the code, which is used for callable in both mutable and immutable collections. It depends on the requirement the set default methods will be used in the various areas.
How does set work in Kotlin?
The kotlin set is the interface that can be used to store and set the datas or elements in the memory list. It is the generic and unordered collection of elements that does not support with the duplicate elements, and the interface is immutable in nature, and its methods support with read-only functionality of the set collections. It has several functions, and it will be called and used it as the abstract model; the elements are present it as the collection, and it returns the boolean statements if the condition is true, it will execute the method like contains() else it will terminate or exist the method if the condition is to be false.
Like that each and every set interface methods have their own default methods and its behaviours for to perform the operations in the application, it returns the null value or if the collection set is to be empty so there are no values declared or stored in the list. Similar to the list interface here, the indexof() method identifies the index of the mentioned and given elements that match the predicate that does not contain the collection. The set elements in the original set it does not allow the duplicate elements, so the values are iterable, and it will return the original collection as well as the given element.
Examples of Kotlin set
Here are the following examples of Kotlin set:
Example #1
Code:
fun main(args: Array<String>)
{
val seta = setOf("January", 1, "February", 2, "March",3,"April",4,"May",5,"June",6,"July",7,"August",8,"September",9,"October",10,"November",11,"December",12)
val setb = setOf<String>("Tamil", "English", "Computer Science")
println(seta)
println(setb)
val setc = setOf('A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
for (i in setc)
println(i)
val setd = setOf<String>("String", "Integer", "Double", "Float", "Char", "Long","Short")
val sete = setOf<Int>(41,42,43,44,45)
println("The total size of set is: ${setd.size}")
println("Please check whether the set variable contains integer or not: ${setd.contains("Integer")}")
println("The given set contains the char type: ${setd.contains("Char")}")
println("Element at index 43 is: ${setd.elementAt(43)}")
println("The index of String type is: ${setd.indexOf("String")}")
println("The index of Long type is: ${setd.indexOf("Long")}")
println("Please find the last index of Short is: ${setd.lastIndexOf("short")}")
println("First element in set: ${setd.first()}")
println("Last element in set: ${setd.last()}")
println("Please check whether the set collection has empty or not: ${setd.isEmpty()}")
println("No. of elements in set are: ${sete.count()}")
println("Maximum element in the set are : ${sete.maxOrNull()}")
println("Minimmum element in set: ${sete.minOrNull()}")
println("Sum of elements in set: ${sete.sum()}")
println("Average of elements in set: ${sete.average()}")
val setf = mutableSetOf("LCD TV", 234, 3.43f, 'C', "LED TV")
val setg = mutableSetOf<String>("LED TV", "LCD TV", "PC", "Laptop", "Mobile", "Tablet")
println(setf)
println(setg)
val seth = mutableSetOf<String>("Samsung", "Sony", "Onida", "BPL", "LG")
println(seth)
seth.add("Airtel")
println(seth)
seth.remove("BPL")
println(seth)
seth.clear()
println(seth)
val seti = setOf(3,6,9,12,15,18,21,24,27,30)
val setj: Set<Any> = setOf(4,8,12,16,20,24,"Multiplication of 4","Table")
println("Welcome To My domain its the first example taht related to the kotlin set interface")
for(element in seti){
println(element)
}
println("Thank you users for spenting the time with us")
for(element in setj){
println(element)
}
val setk: Set<Any> = setOf(5,10,15,20,25,"Multiplication of 5","Table")
val setl = setOf(6,12,18,24,30)
println("Your set collection datas are")
for(element in setk){
println(element)
}
println("setk.contains\"Multiplication\"")
println(setk.contains("Multiplication"))
println("setk.contains(20)")
println(setk.contains(25))
println("setk.containsAll(setl)")
println(setk.containsAll(setl))
}
Output:
In the above example, we used some set default methods and other basic operations.
Example #2
Code:
interface Second {
val x : Int
val y : String
get() = "Welcome To My Domain its the first example that related to the kotlin set interface"
fun Sample1()
}
class secondClass : Second {
override val x : Int
get() = 43
override fun Sample1()
{
println("Have a Nice Day users please try again")
}
}
class NewEmployees
{
var ename: String = ""
var eid: Int = 0
fun employeeDetails(n1: String, q: Int) {
ename = n1
eid = q
println("Please see the below new employee name: $ename")
println("Please see the NewEmployees id: $eid")
}
}
fun main()
{
var ob1 = NewEmployees()
val empset=setOf("Arun",20000,"Kumar",20002,"Raman",20003)
for(j in empset){
println(j)
}
ob1.employeeDetails("Sivaraman", 20001)
println("ename of the new NewEmployees: ${ob1.ename}")
}
Output:
The second example we used was to store the employee details using the set collections.
Example #3
Code:
fun main(args: Array<String>)
{
val firstSet = setOf("First" , "Second", "Third")
val secondSet = setOf( 'F' , 'S' , 'T' )
val thirdSet = setOf( 8 ,2 , 2 , 0 )
for(i in firstSet)
print( i )
println()
for(i in secondSet)
print( i )
println()
for(i in thirdSet)
print( "$i ")
val num = setOf(9 ,8, 7, 4, 5, 6, 1, 2)
println("Total number of element in the set is: "+num.count())
println("maximum element in the set is: "+num.maxOrNull())
println("minimum element in the set is: "+num.minOrNull())
println("The sum of the elements in the set is: "+num.sum())
println("The average of elements in the set is: "+num.average())
}
Output:
We used the final example to calculate the maximum, minimum, and other mathematical operations in the set elements.
Conclusion
The kotlin collection is one of the most important and utilized packages in real-world applications. It is most likely in the other language like java, etc. But some similar differences utilize the methods in the code to call the instance and pass the parameters in the methods.
Recommended Articles
This is a guide to Kotlin set. Here we discuss the introduction, syntax and working of set in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –