How to convert Enumeration to Seq/List in scala?

Freewind picture Freewind · Mar 3, 2011 · Viewed 10.1k times · Source

I'm writing a servlet, and need to get all parameters from the request. I found request.getParameterNames returns a java.util.Enumeration, so I have to write code as:

val names = request.getParameterNames
while(names.hasMoreElements) {
    val name = names.nextElement
}

I wanna know is there any way to convert a Enumeration to a Seq/List, then I can use the map method?

Answer

Debilski picture Debilski · Mar 3, 2011

Use JavaConverters

See https://stackoverflow.com/a/5184386/133106

Use a wrapper Iterator

You could build up a wrapper:

val nameIterator = new Iterator[SomeType] { def hasNext = names.hasMoreElements; def next = names.nextElement }

Use JavaConversions wrapper

val nameIterator = new scala.collection.JavaConversions.JEnumerationWrapper(names)

Using JavaConversions implicits

If you import

import scala.collection.JavaConversions._

you can do it implicitly (and you’ll also get implicit conversions for other Java collecitons)

request.getParameterNames.map(println)

Use Iterator.continually

You might be tempted to build an iterator using Iterator.continually like an earlier version of this answer proposed:

val nameIterator = Iterator.continually((names, names.nextElement)).takeWhile(_._1.hasMoreElements).map(_._2)

but it's incorrect as the last element of the enumerator will be discarded. The reason is that the hasMoreElement call in the takeWhile is executed after calling nextElement in the continually, thus discarding the last value.