The elementAtOrElse()
method of HashSet
returns the element at the given index. If the index is greater than the length of the set
then the defaultValue
function is invoked and the value returned from the function is returned.
fun <T> Iterable<T>.elementAtOrElse(
index: Int,
defaultValue: (Int) -> T
): T
This method takes two parameters:
index
: This is the index of the element to be returned.
defaultValue
: This is a function that will be invoked when the index is greater than the length of set
.
This method returns the element at the given index.
The code below demonstrates how to use the elementAtOrElse()
method:
fun main() { //create a new HashSet which can have String type as elements var set = hashSetOf<String>() // add two entries set.add("1") set.add("2") println("\nThe set is : $set") // get element at index 1 var ele = set.elementAtOrElse(1) {"default value"} println("\nset.elementAt(2) : $ele") // get element at index 3 ele = set.elementAtOrElse(3) {"default value"} println("\nset.elementAt(3) : $ele") }
Line 3: We create a new HashSet
object with the name set
. We use the hashSetOf()
method to create an empty HashSet
.
Lines 6 to 7: We add two new elements, (1,2)
, to the set
using the add()
method.
Line 12: We use the elementAtOrElse
method with a 1
as an argument. The elementAtOrElse
checks for the element at index 1
. In our set
, the element 2
is present in index 1
, so it is returned.
Line 16: We use the elementAtOrElse
method with a 3
as an argument. The elementAtOrElse
checks for the element at index 3
. In our set
, there is no element present in index 3
, so the defaultValue
function is invoked. The defaultValue
function returns default value
as result.
RELATED TAGS
CONTRIBUTOR
View all Courses