我需要将表中的所有值与空格分开,最后将它们添加到List / Collection中。
我的代码
val keywords = scala.collection.mutable.SortedSet[String]()
val connection = DriverManager.getConnection("jdbc:postgresql:<Conn Details>", "<DBNAME>", "<PASSWD>")
val rs = connection.createStatement()
val res = rs.executeQuery("select nom from ip.interest_points where in_use = cast(1 as bit)")
while (res.next) {
keywords += res.getString("nom")
}
print (keywords)
返回
TreeSet(AOC Les Halles, Adele - Réseau Art Contemporain Lyon
Métropole, Amphithéâtre des Trois Gaules, Ancien Hôpital de
l'Antiquaille, Ancienne Gare des Brotteaux...)
我想从“nom”中拆分值,然后将其附加到关键字Sorted Set。
keywords += res.getString("nom").split(" ")
以上代码是我尝试过的,但是没有用。
预期输出
TreeSet(AOC,Les,Halles, Adele,-,Réseau,Art,Contemporain,Lyon...)
编辑:
keywords += res.getString("nom").split(" ").toString
gives ([Ljava.lang.String;@ff5b51f .... )
答案 0 :(得分:2)
String.split()返回Array
。你不能+=
一个SortedSet和一个数组。使用第一个的所有值创建一个新的SortedSet,然后添加两个集。
像这样:
while (res.next) {
val names = scala.collection.mutable.SortedSet[String]()
val interestPoints = res.getString("nom").split(" ")
for (interestPoint <- interestPoints ){
names += interestPoint
}
keywords = keywords ++ names
}
或类似的东西:
while (res.next) {
val interestPoints = res.getString("nom").split(" ")
keywords ++= interestPoints
}
+
通常用于向集合添加单个元素,++
通常用于连接两个集合。
如果您正在使用不可变集合,我知道ArrayOps
有一个方法toSet
,它转换为不可变集合。
答案 1 :(得分:1)
你的问题是你正试图在scala中编写java代码。 :)
我认为,如果你试图保持惯用,并利用你正在使用的语言的原生特性,你会发现许多看起来乏味且难以做到的事情变得简单而优雅。 / p>
或许这样的事情:
new Iterator[String] {
def hasNext = res.next
def next = res.getString("nom")
}
.flatMap(_.split(" "))
.to[SortedSet]