对于Java,如果要获取一个map的所有key可以通过keySet()
,获取所有的value的值调用values()
- 那么对于scala,有更加统一的方式
scala> val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 10, Bob -> 3, Cindy -> 8)
//获取所有的key
scala> val nameList = scores.map(_._1)
nameList: scala.collection.immutable.Iterable[String] = List(Alice, Bob, Cindy)
//获取所有的value
scala> val scoreList = scores.map(_._2)
scoreList: scala.collection.immutable.Iterable[Int] = List(10, 3, 8)
- 同样对于Tuples可以使用一样的方法
scala> val scores = List((1, "Alice", 10), (2, "Bob", 30), (3, "Cindy", 50))
scores: List[(Int, String, Int)] = List((1,Alice,10), (2,Bob,30), (3,Cindy,50))
//获取所有Tuples的第3个元素
scala> scores.map(_._3)
res1: List[Int] = List(10, 30, 50)
- 反向操作可以使用zip,将两个list转换为一个map,其中一个list作为key,另一个作为value
scala> val keyList = List("Alice", "Bob", "Cindy")
keyList: List[String] = List(Alice, Bob, Cindy)
scala> val valueList = List(10, 3, 8)
valueList: List[Int] = List(10, 3, 8)
scala> val scores = keyList.zip(valueList).toMap
scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 10, Bob -> 3, Cindy -> 8)