【问题标题】:Reduce Map values concurrently同时减少 Map 值
【发布时间】:2017-02-24 19:47:29
【问题描述】:

我有字符串键和 Seq[Int] 值的映射。如何将每个键的 Seq[Int] 同时减少为单个 Int 值。

例如:

 Map("xxx" -> (1 to 10), "yyy" -> (100 to 200)) 

应该简化为

 Map("xxx" -> 55, "yyy" -> 15150)

同时针对 Map 中的每个键。

【问题讨论】:

    标签: scala concurrency


    【解决方案1】:

    您可以对 Map 和 Range 使用并行集合 例如

    val x= Map("xxx" -> (1 to 10), "yyy" -> (100 to 200)) 
    x.par.map{case (a,b)=>(a,b.par.sum)}
    

    【讨论】:

      【解决方案2】:

      以下内容应该可以使用 Futures。

      import scala.concurrent.ExecutionContext.Implicits.global
      import scala.concurrent.{Future, Await}
      import scala.concurrent.duration.Duration
      
      val data = Map("xxx" -> (1 to 10), "yyy" -> (100 to 200))
      Await.result(Future.sequence(data.map({ case (x,y) => Future { x -> y.sum } })), Duration.Inf).toMap
      
      res1: scala.collection.immutable.Map[String,Int] = Map(xxx -> 55, yyy -> 15150)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-19
        • 2019-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多