Scala中List集合与Map集合的相互转换

List集合转换成Map集合

object Demo{
    def main(args: Array[String]): Unit = {
        // 创建一个List集合对象
        val list: List[String] = List("dog", "tiger", "lion", "cat", "panther", "eagle")
        // 映射(转换)
        // 可以看到List集合里是一个个元组
        val tuples: List[(String, Int)] = list.map(x=>{(x, x.length)})
        println(tuples)
        
        // 将List转换成Map
        val map: Map[String, Int] = tuples.toMap
        println(map)
        
    }
}

结果为:
List((dog,3), (tiger,5), (lion,4), (cat,3), (panther,7), (eagle,5))
Map(lion -> 4, tiger -> 5, dog -> 3, eagle -> 5, panther -> 7, cat -> 3)

注意:
看下面一段代码

object Demo1{
    def main(args: Array[String]): Unit = {
        
      val list: List[String] = List("dog", "tiger", "lion", "cat", "panther", "eagle")
      val tuples: List[(Int, String)] = list.map(x => {(x.length, x)})
      println(tuples)
      val map: Map[Int, String] = tuples.toMap
      println(map)  
    }
}

结果为:
List((3,dog), (5,tiger), (4,lion), (3,cat), (7,panther), (5,eagle))
Map(3 -> cat, 5 -> eagle, 4 -> lion, 7 -> panther)

可以看到输出的结果,转换成Map集合后, 少了dog和tiger, 为什么呢???
因为dog和cat的长度为3, eagle和tiger的长度为5, 当转换成Map集合, 此时dog和cat的键为3, eagle和tiger的键为5, 我们知道, Map集合中如果键相同, 会发生覆盖, 就会少去其中一个.





Map集合转换成List集合

代码如下:;

object Demo2{
   def main(args: Array[String]): Unit = {
        val list: List[String] = List("dog", "tiger", "lion", "cat", "panther", "eagle")
        
        val tuples: List[(String, Int)] = list.map(x => (x, x.length))
        println(tuples)
        //  List集合转换成Map集合
        val map: Map[String, Int] = tuples.toMap
        println(map)

        // Map集合转换成List集合
        // 使用toList方法
        val list1: List[(String, Int)] = map.toList
        println(list1)
   }
}

结果为:
List((dog,3), (tiger,5), (lion,4), (cat,3), (panther,7), (eagle,5))
Map(lion -> 4, tiger -> 5, dog -> 3, eagle -> 5, panther -> 7, cat -> 3)
List((lion,4), (tiger,5), (dog,3), (eagle,5), (panther,7), (cat,3))

你可能感兴趣的:(Scala)