Scala aggregate functions groupBy source code analysis

Here Insert Picture Description

groupBy source code analysis

  1. Create a map object variable m -> [k: K v: mutable.Bulder [A , Repr] ]
    Here Insert Picture Description
    where Bulder elements A, type Repr constructed, it can add elements to the + = constructor, by It returns a result set to give any type!

  2. Through the collection, add elements to m, the key to pass over the elements in the set () calculation result returned by the function F, if the key is not in the m, then create an element of type A, type of construction is Repr of Builder object into a value in that point and so bldr Builder object to add elements elem bldr (in fact is added to the value m of elem)

Example: the first f () evaluates to 1, elem is "a", is the first time, to create a new Builder V, this case m = (1 -> ( "a")), a second Ci f () calculations or 1, elem is "b", this case m = (1 -> ( "a", "b")), the third f () results into a 2, elem is " c ", since the key-> 2 the first time, create a new Builder, case m = (1 -> (" a "," b "), 2 -> (" c "))

此时m->k=f(elem),v=elems
  1. Create a constructor b, element type is Tupple2 (K, Repr), type of construction is Map (K, Repr), traversing m, add k and v to b, the introduction of m data constructor b call result output set

Summary: groupBy passed parameters f (A) => K, A is the set of elements of the type called function, K is the key map output.
The output of the map is a set of types of value type function call
Example:

    println(Map[Int, Int]((1, 2), (2, 3), (3, 4), (4, 5))
      .groupBy(kv => 1))

    println(Map[Int, Int]((1, 2), (0, 3), (2, 3), (3, 2))
      .groupBy(kv => kv._1+kv._2))

result:
Here Insert Picture Description

Released two original articles · won praise 4 · Views 1503

Guess you like

Origin blog.csdn.net/Mr_kidBK/article/details/104735780