4 - Set - Setof
4 - Set - Setof
Syntax:
Description:
Kotlin
fun main(args: Array<String>)
{
//declaring a set of strings
val seta = setOf("Geeks" , "for", "geeks")
//declaring a set of characters
val setb = setOf( "G" , "f" , "g" )
//declaring a set of integers
val setc = setOf( 1 ,2 , 3 , 4 )
Output:
Geeksforgeeks
Gfg
1 2 3 4
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
Output:
We can get the first and element of a set using first() and last() functions.
Kotlin program –
Kotlin
Output:
Set Basics –
Here we will discuss basics functions like count(), max(), min(), sum(),
average().
Kotlin program of using basic functions –
Kotlin
Output:
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
var num = 5
println("The set contains the element $num or not?" +
" "+captains.contains(num))
Output:
Kotlin
Output :
seta.isEmpty() is true
seta == setb is true
[]
Sure, here’s an example code that demonstrates how to use the setOf()
function in Kotlin
Kotlin
fun main() {
val fruits = setOf("apple", "banana", "cherry")
println("Fruits: $fruits")
println("Does the set contain an apple? $hasApple")
println("Does the set contain an orange? $hasOrange")
output:
Fruits: [apple, banana, cherry]
Does the set contain an apple? true
Does the set contain an orange? false
apple
banana
cherry
1. Since the set is immutable, you cannot add or remove elements from it once
it has been created. This may be a disadvantage if you need to modify the
contents of the set during the runtime of your program.
2. If you need to create a mutable set that can be modified at runtime, you will
need to use a different function, such as mutableSetOf().
Similar Reads
Android - Create Group Kotlin | Language for
BarChart with Kotlin Android, now Official by
Google