Scala groupBy Identity

Posted July 26, 2022 by Rohith ‐ 1 min read

Scala has different ways to solve a given problem. In this blog, we will discuss using groupBy identity.

groupBy(identity) Usage

groupBy(identity) is used when we want to map each element in a seq to itself.

Example 1:

val numList: List[Int] = Range(0, 3).toList
val groupByIdentity: Map[Int, List[Int]] = numList.groupBy(identity)

Output

val numList: List[Int] = List(0, 1, 2)
val groupByIdentity: scala.collection.immutable.Map[Int,List[Int]] = HashMap(0 -> List(0), 1 -> List(1), 2 -> List(2))

Example 2:

val numList: List[Int] = Range(0, 3).toList
val groupByIdentity: Map[Int, List[Int]] = (numList ++ numList).groupBy(identity)

Output

val numList: List[Int] = List(0, 1, 2)
val groupByIdentity: scala.collection.immutable.Map[Int,List[Int]] = HashMap(0 -> List(0, 0), 1 -> List(1, 1), 2 -> List(2, 2))

groupBy(identity) in mapReduce

groupBy(identity) can be a great help in mapReduce operation.

Extending above Example 2: Let’s find the occurrences of each element in the list.

val numList: List[Int] = Range(0, 3).toList
val groupByIdentity: Map[Int, Int] = 
    (numList ++ numList)
        .groupBy(identity)
        .mapValues(_.size)
        .toMap

Output

scala.collection.immutable.Map[Int,Int] = Map(0 -> 2, 1 -> 2, 2 -> 2)

Subscribe For More Content