Turning Map(“a” -> 2, “b” -> 1) into seq(“a”,“a”,“b”) using map

后端 未结 2 1401
夕颜
夕颜 2021-01-23 16:52

I am trying to turn a Map("a" -> 2, "b" -> 1) into seq("a","a","b") through the map function, Currently I am trying to ru

2条回答
  •  甜味超标
    2021-01-23 17:39

    you can do something like this: Use fill method of GenTraversableFactory def fill[A](n: Int)(elem: => A): CC[A] from the definition of fill we can see that it takes an integer and an element. Integer tell how many times we need to fill the given element.

    object Demo extends App {
    
      val x = Map("a" -> 2, "b" -> 1)
    
      val p: Seq[String] = x.flatMap { tuple =>
        List.fill(tuple._2)(tuple._1)
      }.toSeq
    
      print(p)
    //output: List(a, a, b)
    }
    

    I Hope it helps!!!

    If you want to avoid tuple._1 and tuple._1 you can use the following approach.

    object Demo extends App {
    
      val x = Map("a" -> 2, "b" -> 1)
    
      val p: Seq[String] = x.flatMap { case (key, value) =>
        List.fill(value)(key)
      }.toSeq
    
      print(p)
    //output: List(a, a, b)
    }
    

提交回复
热议问题