1. map中获取index
val x = list.zipWithIndex.flatMap(x =>
anotherFunction(x._1.param1.param2List.size * x._1.multiplier,
x._1, x._1.param1.param2List(x._2)))
2. List转Map, List[Tuple3] to Map[String,String]
val prices = dao.getPricing.map { p => ( p._1.toString, p._2+" $"+p._3)} toMap
val prices: Map[String, String] = dao.getPricing.map {
case (id, label, fee) =>
(id.toString -> (label + " $" + fee))
} (collection.breakOut)
3. Json序列化
import scala.util.parsing.json.JSONObject
// import scala.util.parsing.json.JSONArray 序列化List类型的对象
val mymap = array.map {
case 1 => ("A", 1)
case 2 => ("B", 2)
case 3 => ("C", 3)
} .toMap
# 只需一行
JSONObject(mymap).toString()
4. Json反序列化
import scala.util.parsing.json.JSON
val json = JSON.parseFull(string) //将JSON格式字符串解读成Some
val any = json.get //将some格式中的内容get出来,得到一个any类型的值
any match {
case map: Map[String, String] =>map //匹配成功返回我们需要的Map类型数据
case _ => { //匹配失败返回Null值
println("匹配失败");
null
}
}
5. String.split
split函数主要有两种参数形式:
def split(arg0: String): Array[String] // 等同于split(arg0, 0)
def split(arg0: String, arg1: Int): Array[String]
- arg0:正则表达式,代表分割的边界
- arg1:限定分割后子串的个数
// 当arg1大于0时,它限制arg0最多成功匹配arg1-1次,也就是说字符串最多被分成arg1个子串。
//此时split会保留分割出的空字符串,直到达到匹配上限
scala> "a-b-c".split("-", 2)
res38: Array[String] = Array(a, b-c)
scala> "a-b-c".split("-", 4)
res39: Array[String] = Array(a, b, c)
scala> "-a-b-c--".split("-", 3)
res40: Array[String] = Array("", a, b-c--)
scala> "-a-b-c--".split("-", 6)
res41: Array[String] = Array("", a, b, c, "", "")
scala> "-a-b-c--".split("-", 5)
res42: Array[String] = Array("", a, b, c, -)
scala> "-a-b-c--".split("-", 8)
res43: Array[String] = Array("", a, b, c, "", "")
// 当arg1等于0时,split函数会尽可能多的匹配arg0,但不再保留处于末尾位置的空字符串
scala> "a-b-c".split("-", 0)
res48: Array[String] = Array(a, b, c)
scala> "a-b-c---".split("-", 0)
res49: Array[String] = Array(a, b, c)
scala> "-a--b--c---".split("-", 0)
res50: Array[String] = Array("", a, "", b, "", c)
scala> "".split("-", 0)
res51: Array[String] = Array("")
// 当arg1小于0时,split函数会尽可能多的匹配arg0,并且保留末尾的空字符串
scala> "a-b-c".split("-", -1)
res52: Array[String] = Array(a, b, c)
scala> "-a--b--c-".split("-", -1)
res53: Array[String] = Array("", a, "", b, "", c, "")
6. Java List to Scala List
Since Scala 2.8 this conversion is now built into the language using:
import scala.collection.JavaConversions._
...
lst.toList.foreach{ node => .... }
works. asScala
did not work
7. Scala multiMap
// This is your list of (A, B)
val l = List((1, "hi"),
(2, "there"),
(1, "what's"),
(3, "up?"))
// Group it and snip out the duplicate 'A'
// i.e. it initially is Map[A, List[(A, B)]] and we're going to convert it
// to Map[A, Set[B]]
val m = l.groupBy(e => e._1).mapValues(e => e.map(x => x._2).toSet)
println(m)
// Prints: Map(3 -> Set(up?), 1 -> Set(hi, what's), 2 -> Set(there))