10: Coding Scala Way – groupBy, mapValues & identity

Java developers need to learn Coding Scala Way. Scala way of coding is quite different & you need to unlearn Java way of coding

Question: Given a list of numbers, how will you group the numbers by how many times they occur? for example output for “List(3, 3, 4, 5, 5, 5)” is List((3,2), (4,1), (5,3)).

Pre Java 8 way – imperative style

Output:

{3=2, 4=1, 5=3}

Java 8 way – Functional Programming (i.e FP) style

Output:

{3=2, 4=1, 5=3}

groupBy in Scala FP

Before we provide the solution, the Scala Way, “groupBy” function to the rescue. Here is an example:

Output:

Scala Way – FP style

Output:

Explanation:

Step 1: input.groupBy { x => x } returns a “Map[Int, List[Int]]”. In the above example it returns

Step 2: The “num” is the Map “key” and “times” is the value.

The above output is not sorted by “num”.

Step 3: Sort by “num”, which is the “first value” i.e. “_1” in the any given input i.e. “_

Scala Way 2: “identity” & “mapValues”

The “scala.Predef” object has the following function

Q: What does Predef.identity do in Scala?
A: “identity” simply returns its argument. It can be handy sometimes to pass to higher-order functions. In the above example,

instead of doing

You can do

Finally, you can write the whole thing like a DSL (Domain Specific Language)


800+ Java & Big Data Interview Q&As

Top