Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

drop
hashset
kotlin
communitycreator

How to use the drop method of the HashSet in Kotlin

Programming Bytes

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 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")

}
Using the drop() method

Code explanation

  • 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

drop
hashset
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring