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)

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 )

Arulkumaran Kumaraswamipillai

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

800+ Java Interview Q&As – ♥Free | ♦FAQs

open all | close all

Pressed for time? 200+ Java Interview FAQs

open all | close all

16 Technical Key Areas to be a top-notch

open all | close all

100+ Java Tutorials – Step by step

open all | close all

100+ Java Coding Exercises

open all | close all

How good are your

open all | close all