Georg Heiler
Georg Heiler

Reputation: 17676

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

Upvotes: 0

Views: 1324

Answers (1)

Vidya
Vidya

Reputation: 30310

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)

Upvotes: 3

Related Questions