Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

scala - Turning Map("a" -> 2, "b" -> 1) into seq("a","a","b") using map

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 run the code below giving me the desired result.

Is there a smarter way to do this? Possibly a better way through the map function?

    var multiset : Seq[T] = Seq[T]()
    var variables : Seq[T] = data.map(x => x._1).toSeq
    var variableCounts : Seq[Int] = data.map(x => x._2).toSeq
    for(x <- 0 until variables.length){
        for(y <- 0 until variableCounts(x))
            multiset = multiset :+ variables(x)
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...