How to use the drop method of the HashSet in Kotlin
Overview
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.
Syntax
fun <T> Iterable<T>.drop(n: Int): List<T>
Arguments
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.
Return value
This method returns a list.
Code example
The code written below demonstrates how to use the drop() method:
fun main() {//create a new HashSet which can have integer type as elementsvar set: HashSet<Int> = hashSetOf<Int>()// add four entriesset.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")}
Code explanation
-
Line 3: We create a new
HashSetobject with the nameset. We use thehashSetOf()method to create an emptyHashSet. -
Lines 6–9: We add four new elements (1,2,3,4) to the
set, using theadd()method. -
Line 13: We use the
dropmethod by passing2as an argument to the function. Thedropmethod creates a new list from thesetby dropping the first two elements. The returned list is[3,4].