# 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)).

Output:

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

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,

You can do

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

overall bird-eye view of the Java Environment together with so many useful questions. I am totally impressed with the way you have learned Java.

Yours Sincerely
Ye Tun Oo ( More )

#### Most visited in last 30 days

Mechanical Engineer to freelance Java developer within 3 years. Freelancing since 2003 for the major banks, telecoms, retail & government organizations. Attended 150+ Java job interviews, and most often got 3-6 job offers to choose from. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training. join my LinkedIn group.

Posted in Scala way of coding