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)

Print Friendly
The following two tabs change content below.
Arulkumaran Kumaraswamipillai
Mechanical Engineering to Java freelancer since 2003. 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.
Arulkumaran Kumaraswamipillai

Mechanical Engineering to Java freelancer since 2003. 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+ Interview Q&As ♥Free|♦FAQ (Mouse Hover for Full Text)

open all | close all

200+ Java FAQs – Memory Joggers

open all | close all

16 Java Key Areas to be a top-notch

open all | close all

80+ Java Tutorials – Step by step

open all | close all

100+ Java Coding Exercises

open all | close all

How good are your "Career Skills"?

open all | close all