Kotlin Set : setOf()
Kotlin Set interface is a generic unordered collection of elements and it does not contain duplicate elements. Kotlin supports two types of sets mutable and immutable.
setOf() is immutable means it supports only read-only functionalities and mutableSetOf() is mutable means it supports read and write both functionality.
fun <T> setOf( vararg elements: T): Set<T>
- This function returns a new read only set of given elements.
- The elements are iterated over, according as they are stored .
Kotlin program of setOf() function :
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 program of using index –
The element at index 2 is: Root The index of element is: 1 The last index of element is: 4
Set first and last element –
We can get the first and element of a set using first() and last() functions.
Kotlin program –
The first element of the set is: 1 The last element of the set is: Dhawan
Set Basics –
Here we will discuss basics functions like count(), max(), min(), sum(), average().
Kotlin program of using basic functions –
The number of element in the set is: 8 The maximum element in the set is: 8 The minimum element in the set is: 1 The sum of the elements in the set is: 36 The average of elements in the set is: 4.5
contains() and containsAll() functions –
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 –
The set contains the element Dhawan or not? true The set contains the element 5 or not? false The set contains the given elements or not? true
Checking equality of empty sets and use of isEmpty() functions –
fun <T> setOf(): Set<T>
This syntax returns an empty set of specific type.
Kotlin program of using isEmpty() function –
seta.isEmpty() is true seta == setb is true