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

The following two tabs change content below.
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. 1,350+ paid memberships.

By topics – 800+ Q&As ♥ Free ♦ FAQ

open all | close all

Java 200+ FAQs – Quick Brushup

open all | close all

100+ Java Tutorials step by step

open all | close all

13+ Tech Key Areas to standout

open all | close all

Java coding exercises

open all | close all
Top