Samstag, 20. Februar 2010

How to transform a List into a java.util.List



implicit def toJavaList[A](i: scala.Iterable[A]): java.util.List[A] = {
val result = new java.util.ArrayList[A]
i.foreach(result.add)
java.util.Collections.unmodifiableList[A](result)
}


Or, if you don't need a immutable List:


implicit def toJavaMutableList[A](i: scala.Iterable[A]): java.util.List[A] = {
val result = new java.util.ArrayList[A]
i.foreach(result.add)
result
}



Example using javaMutableList :



val names = List("1","2","3","4","5","6","7")

val jlist: java.util.List[String] = names
jlist: java.util.List[String] = [1, 2, 3, 4, 5, 6, 7]

val shuffled = java.util.Collections.shuffle(jlist)
shuffled: Unit = ()

println(jlist)
[4, 5, 3, 7, 2, 6, 1]

Mittwoch, 17. Februar 2010

Arabic-Roman numerals converter written in Scala

A simple arabic to roman numeral converter written in Scala


import scala.collection.SortedMap

def roman(x:Int): String = {

val romanLiteral = SortedMap(1000 -> "M", 900 -> "CM", 500 -> "D", 400 -> "CD",
100 -> "C", 90 -> "XC", 50 -> "L", 40 -> "XL", 10 -> "X", 9 -> "IX", 5 ->
"V", 4 -> "IV", 1 -> "I")

val arab = romanLiteral.keySet.toList.reverse

def r(n:Int,idx:Int,romanNumber:StringBuilder): String = {

val a = arab(idx)

if (n==0)
romanNumber.toString
else if ( n >= a )
r( n-a, idx, romanNumber append romanLiteral(a) )
else
r( n, idx+1, romanNumber )
}

r(x,0,new StringBuilder())

}

(1 to 100).foreach( x => printf( "%s=%s\n", x, roman(x) ))