简体   繁体   中英

scala iterate java hashSet

I wonder how to idiomatically iterate a java.util.HashSet in Scala. Currently, I am using the java iterators in a while loop which does not seem to be great.

Additionally, I wonder if the mutable growable buffer is efficient or if there is a possibility to avoid the creation of unnecessary objects.

import java.util

import scala.collection.generic.Growable
import scala.collection.mutable

val javaSet = new util.HashSet[String]()
javaSet.add("first")
javaSet.add("second")

val result: collection.Seq[String] with Growable[String] = mutable.Buffer[String]()
val itr = javaSet.iterator

while (itr.hasNext) {
  result += itr.next
}

result

edit

Would a stream be better? Apache Spark: Effectively using mapPartitions in Java

Since you are using a Java HashSet apparently, do this first:

import scala.collection.JavaConverters._

This lets you turn Java collections into Scala collections, which are much easier to work with, using asScala .

So if you have an instance of HashSet called set , you can do this:

set.asScala.map(value => doSomething(value))

Or whatever you want to do like filter , foldLeft , etc.

FYI, the above example can be syntactically sugared to this:

set.asScala.map(doSomething)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM