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

后端 未结 2 1381
夕颜
夕颜 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:34

    I am not sure exactly what the shape of your data is. That part is a little bit unclear from the question.

    Map('a' -> 3, 'b' -> 1)
    

    Is indeed a Map. Whereas

    ('a' -> 3, 'b' -> 1)
    

    desugars in a Tuple

    (('a', 3), ('b', 1))
    

    If it is the former case you can fold like this

    val m : Map[String, Int] =  Map("a" -> 2, "b" -> 1) 
    val res = m.foldLeft(List[String]())((a, b) => a ++ List.fill(b._2)(b._1))
    

    here res will be List('a', 'a', 'b')

    What is going on here is that we start with an empty accumulator, iterate through the key-value pairs of the Map, create a list that repeats the given key, value times and concat it to the accumulator

    The latter is unfortunately a little harder without using something like Shapeless since in Scala 2 the type information will get lost when converting from a Tuple. You need to do some type juggling with the annotations

    val ml = ("a" -> 2, "b" -> 1).productIterator
    ml.foldLeft(List[String]())((a, b) => b match{ 
       case (k: String, v : Int) => a ++ List.fill(v)(k)
    })
    

提交回复
热议问题