x89a10
x89a10

Reputation: 691

Get and remove an arbitrary element from a mutable HashSet in Scala

How do you get and remove an arbitrary element from a mutable HashSet in Scala (similar to python set pop method)? Also what would be the performance of the api?

Upvotes: 0

Views: 988

Answers (2)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41987

@Andrey's answer above should suffice to answer your question as he said you can use .head function to pop an element.

Here are some more details.

Sets are one of the collection libraries of Scala which provide both mutable and immutable methods. If you want specific element to be removed from Sets then there is - and + methods. - method is used for removing an element from a Set and a new Set is returned. Similarly + method is used for adding an element in a Set which also returns a new Set with the element added. So you can write pop and set functions that will remove and add specific elements.

def popFromSet[T](set: Set[T], stringToPop: T) = {
  set - stringToPop
}

def setToSet[T](set: Set[T], stringToPop: T) = {
  set + stringToPop
}

And you can use them as

popFromSet(stringSet, "second")
setToSet(popFromSet(stringSet, "second"), "second2") 
popFromSet(intSet, 2)
....

List way

You can do the above Set to List

If you have a HashSet as

Set("first", "second", "third")

You can get the second element popped out by doing

val hashList = hashSet.toList
hashList(hashList.indexOf("second"))

and if you want to remove the second element from the HashSet then

hashSet - hashList(hashList.indexOf("second"))

I hope the answer is helpful

Upvotes: 1

Andrey Tyukin
Andrey Tyukin

Reputation: 44992

For extracting and removing elements in undefined order from a mutable hash set, try a combination of head and -= (remove):

import scala.collection.mutable.HashSet

def pop[A](hs: HashSet[A]): A = {
  val a = hs.head
  hs -= a
  a
}

val example = HashSet.empty[Int] ++ (0 to 9)

while (!example.isEmpty) {
  val p = pop(example)
  println("Pop element: " + p)
}

I'm not sure whether it's caching any keys or hashes internally, but afaik it's either just O(1) or amortized O(1).

Upvotes: 3

Related Questions