The drop()
method of the HashSet
in Kotlin returns a new list that is created from the current HashSet
by dropping the first n
elements.
fun <T> Iterable<T>.drop(n: Int): List<T>
This method takes an integer value as an argument. This integer value denotes the number of elements from the beginning of the set
that need to be dropped.
This method returns a list.
The code written below demonstrates how to use the drop()
method:
fun main() { //create a new HashSet which can have integer type as elements var set: HashSet<Int> = hashSetOf<Int>() // add four entries set.add(1) set.add(2) set.add(3) set.add(4) println("\nThe set is : $set") var list = set.drop(2) println("\nset.drop(2) : $list") }
Line 3: We create a new HashSet
object with the name set
. We use the hashSetOf()
method to create an empty HashSet
.
Lines 6–9: We add four new elements (1,2,3,4) to the set
, using the add()
method.
Line 13: We use the drop
method by passing 2
as an argument to the function. The drop
method creates a new list from the set
by dropping the first two elements. The returned list is [3,4]
.
RELATED TAGS
CONTRIBUTOR
View all Courses