如何在scala中将枚举转换为Seq / List? [英] How to convert Enumeration to Seq/List in scala?

查看:114
本文介绍了如何在scala中将枚举转换为Seq / List?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个servlet,需要从请求中获取所有参数。我发现 request.getParameterNames 返回一个 java.util.Enumeration ,所以我必须将代码编写为:

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
}

我想知道有什么方法可以转换 Enumeration Seq / List ,那么我可以使用 map 方法吗?

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

推荐答案

使用JavaConverters

请参见https://stackoverflow.com/a/5184386/133106

使用包装器迭代器

您可以构建包装器:

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

使用JavaConversions包装器

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

使用隐式JavaConversions

如果导入

import scala.collection.JavaConversions._

您可以隐式地执行此操作(并且您还将获得其他Java collecitons的隐式转换)

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

request.getParameterNames.map(println)

连续使用Iterator

您可能很想使用 Iterator.continuously 构建一个迭代器,就像该答案的早期版本一样:

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)

但是我t是不正确的,因为枚举器的最后一个元素将被丢弃。
原因是 takeWhile 中的 hasMoreElement 调用是在调用之后执行的中的nextElement 不断地,从而丢弃最后一个值。

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.

这篇关于如何在scala中将枚举转换为Seq / List?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆