Scala reduceByKey function - use any type that has + method

后端 未结 1 1565
暖寄归人
暖寄归人 2021-02-04 16:03

I am writing a simple function called reduceByKey that takes a collection of (key, numeric) pairs and returns reduced collection by key.

  def redu         


        
相关标签:
1条回答
  • 2021-02-04 17:03

    If you are only interested in numeric values, you can use the standard Numeric type class and do this:

    def reduceByKey[K,V](collection: Traversable[Tuple2[K, V]])(implicit num: Numeric[V]) = {    
      import num._
      collection
        .groupBy(_._1)
        .map { case (group: K, traversable) => traversable.reduce{(a,b) => (a._1, a._2 + b._2)} }
    }
    

    The num implicit parameter serves as an evidence that V is a numeric type, and provides the + operation for this type.

    0 讨论(0)
提交回复
热议问题