簡體   English   中英

從Scala中的可變HashSet中獲取和刪除任意元素

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

如何在Scala中從可變HashSet中獲取和刪除任意元素(類似於python set pop方法)? 另外,api的性能如何?

要從可變哈希集中以不確定的順序提取和刪除元素,請嘗試結合使用head-= (刪除):

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

我不確定它是否在內部緩存任何鍵或哈希,但確實是O(1)或攤銷O(1)

.head的上述答案足以回答您的問題,因為他說您可以使用.head函數來彈出元素。

這里有一些更多細節。

Sets是Scala的集合庫之一,它提供可變方法和不可變方法。 如果要從Sets刪除特定元素,則有-+方法。 -方法用於從Set刪除元素,並返回一個新的Set 類似地, +方法用於在Set添加元素,該方法還返回添加了元素的新Set 因此,您可以編寫popset函數,以刪除和添加特定元素。

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

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

您可以將它們用作

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

列表方式

您可以執行上述SetList

如果您有一個HashSet作為

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

您可以通過執行以下操作彈出第二個元素

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

如果要從HashSet刪除第二個元素,則

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

我希望答案是有幫助的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM