Skip to content

Commit 7f83f63

Browse files
committed
Adding groupMapReduce method to Iterator
1 parent 7b027e2 commit 7f83f63

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Scala (https://www.scala-lang.org)
3+
*
4+
* Copyright EPFL and Lightbend, Inc.
5+
*
6+
* Licensed under Apache License 2.0
7+
* (http://www.apache.org/licenses/LICENSE-2.0).
8+
*
9+
* See the NOTICE file distributed with this work for
10+
* additional information regarding copyright ownership.
11+
*/
12+
13+
package scala.collection
14+
15+
object IteratorExtensions {
16+
implicit class IteratorExtensionsOps[A](private val iter: Iterator[A]) extends AnyVal {
17+
/**
18+
* Partitions this Iterator into a map according to a discriminator function `key`. All the values that
19+
* have the same discriminator are then transformed by the `value` function and then reduced into a
20+
* single value with the `reduce` function.
21+
*
22+
* {{{
23+
* def occurrences[A](as: Iterator[A]): Map[A, Int] =
24+
* as.groupMapReduce(identity)(_ => 1)(_ + _)
25+
* }}}
26+
*
27+
* @note This will force the evaluation of the Iterator.
28+
*/
29+
def groupMapReduce[K, B](key: A => K)(f: A => B)(reduce: (B, B) => B): immutable.Map[K, B] = {
30+
val m = mutable.Map.empty[K, B]
31+
iter.foreach { elem =>
32+
m.updateWith(key = key(elem)) {
33+
case Some(b) => Some(reduce(b, f(elem)))
34+
case None => Some(f(elem))
35+
}
36+
}
37+
m.to(immutable.Map)
38+
}
39+
}
40+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Scala (https://www.scala-lang.org)
3+
*
4+
* Copyright EPFL and Lightbend, Inc.
5+
*
6+
* Licensed under Apache License 2.0
7+
* (http://www.apache.org/licenses/LICENSE-2.0).
8+
*
9+
* See the NOTICE file distributed with this work for
10+
* additional information regarding copyright ownership.
11+
*/
12+
13+
package scala.collection
14+
15+
import org.junit.Assert._
16+
import org.junit.Test
17+
import IteratorExtensions._
18+
19+
final class TestIteratorExtensions {
20+
@Test
21+
def groupMapReduce(): Unit = {
22+
def occurrences[A](as: Seq[A]): Map[A, Int] =
23+
as.iterator.groupMapReduce(identity)(_ => 1)(_ + _)
24+
25+
val xs = Seq('a', 'b', 'b', 'c', 'a', 'a', 'a', 'b')
26+
val expected = Map('a' -> 4, 'b' -> 3, 'c' -> 1)
27+
assertEquals(expected, occurrences(xs))
28+
}
29+
}

0 commit comments

Comments
 (0)