EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala groupBy

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala groupBy

Scala groupBy

Introduction to Scala groupBy

Scala groupBy is the part of collection data structure. As the name suggest it is used to group the elements of collections. This groupBy is applicable for both mutable and immutable collection in scala. Immutable objects are those which are once assigned cannot change their value itself and mutable objects are those whose value is changing very frequently. Also this groupBy converts the List into Map by this we can perform some useful operations on it. It will return us a map which will contain the key value pair.

Syntax and parameters:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Scala groupBy function takes a predicate as a parameter and based on this it group our elements into a useful key value pair map. That means we can convert our List object to Map using groupBy function.

Below we can see the syntax to define groupBy in scala:

groupBy[K](f: (A) ⇒ K): immutable.Map[K, Repr]

In the above syntax we can see that this groupBy function is going to return a map of key value pair. Also inside the groupBy we will pass the predicate as the parameter.

We can see one practical syntax for more understanding:

var l1= List("anc", "ahg", "tyh")
l1.groupBy(x => x.length()).foreach(println)

In this way we can define our groupBy function and convert the list into Map of key value pair. We can use this function with any collection data structure.

How groupBy work in Scala?

Scala groupBy is used to group elements from the collection. It is also used to store the objects and retrieving of the object. groupBy return us Map collection in scala.

We can have a closer look at groupBy syntax how it is working:

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,543 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)

someList.groupBy(obj => obj)

In the above line we can see some list name followed by the groupBy function and inside the groupBy function there is one anonymous function (=>) this function will iterate over all the list element and group the element which have same value as ‘obj’. After that internally it will convert that into HashMap with key value pair and all the elements with the same content into one single group. If the two or more elements are same inside the list then they will map against the same key inside the HashMap.

Let’s have look at its extended, super classes and some known classes in scala.

Extended classes available:

  • Iterable[(K, V)]
  • MapOps[K, V, Map, Map[K, V]]
  • MapFactoryDefaults[K, V, Map, Iterable]
  • Equals

Super classes available:

  • Equals
  • MapFactoryDefaults[K, V, Map, Iterable]
  • MapOps
  • PartialFunction
  • (K)=> V
  • Iterable
  • IterableFactoryDefaults
  • IterableOps
  • Map
  • IterableOnceOps
  • IterableOnce
  • AnyRef
  • AnyRef

Some of the known subclasses available:

  • AbstractMap
  • SeqMap
  • SortedMap
  • Map
  • TrieMap
  • HashMap
  • IntMap
  • ListMap
  • LongMap
  • Map
  • Map1
  • Map2
  • Map3
  • Map4
  • WithDefault
  • SeqMap
  • TreeMap
  • TreeSeqMap
  • VectorMap
  • AbstarctMap
  • AnyRefMap
  • CollisionProofHashMap
  • HashMap
  • LinkedHashMap
  • LongMap
  • SystemProperties
  • ListMap
  • MultiMap
  • OpenHashMap

Hierarchy available:

  • Iterable
  • MapOps
  • Equals
  • UnliftOps
  • IterableOnceExtensionMethods
  • ImmutableMap
  • MutableMap

Example:

Code:

object Main extends App{
// Your code here!
var list1= List("amit", "sumit", "vinit", "ajit", "kavit", "lalit", "lalit", "vinit", "vinit")
var g = list1.groupBy(x => x)
println(g)
}

In the above example first we have defined a list containing some object. This list also contains some duplicate objects as well. After that we are applying the groupBy function to group by same elements. So in our list vinit and lalit it appears to be more than one time so while creation of HashMap it will group all these similar list elements against same key in map.

This is something weried but it is helpful if we want to apply some logic on list based on groupBy of elements on some basis.

Examples of Scala groupBy

Given below are the examples mentioned :

Example #1

In this example we are just applying groupBy for beginners to understand. We are using groupBy on List here.

Code:

object Main extends App{
// Your code here!
// initializing the list
var list1= List("amit", "sumit", "vinit", "ajit", "kavit", "lalit", "lalit", "vinit", "vinit")
println("list before group by is  ::")
println(list1)
//applying groupBy method here
var group1 = list1.groupBy(x => x)
// printing output
println("list after group by is  ::")
println(group1)
}

Output:

Scala groupBy 1

Example #2

In this example we are grouping list of integers.

Code:

object Main extends App{
// Your code here!
// initializing the list
var list1= List(100, 400, 200, 500, 100, 1900, 2000, 400, 400, 19000)
println("list before group by is  ::")
println(list1)
//applying groupBy method here
var group1 = list1.groupBy(x => x)
// printing output
println("list after group by is  ::")
println(group1)
}

Output:

Scala groupBy 2

Example #3

In this example we are grouping elements by on basis of contains method as predicate.

Code:

object Main extends App{
// Your code here!
// initializing the list
var list1= List("amit", "sumit", "sumit", "vinit", "ajit", "kavit", "lalit", "lalit", "vinit", "vinit")
println("list before group by is  ::")
println(list1)
//applying groupBy method here
var group1 = list1.groupBy(_.contains("sumit"))
// printing output
println("list after group by is  ::")
println(group1)
}

Output:

Scala groupBy 3

Example #4

In this method we are passing charAt as predicate inside groupBy method.

Code:

object Main extends App{
// Your code here!
// initializing the list
var list1= List("amit", "sumit", "sumit", "vinit", "ajit", "kavit", "lalit", "lalit", "vinit", "vinit")
println("list before group by is  ::")
println(list1)
//applying groupBy method here
var group1 = list1.groupBy(_.charAt(0))
// printing output ..
println("list after group by is  ::")
println(group1)
}

Output:

we are passing charAt as predicate

Example #5

In this example we are group by the list of integer by checking whether the element is divisible by ‘3’ or not.

Code:

object Main extends App{
// Your code here!
// initializing the list
var list1= List(100, 400, 200, 500, 100, 1900, 2000, 400, 400, 19000)
println("list before group by is  ::")
println(list1)
//applying groupBy method here
var group1 = list1.groupBy(_ % 3)
// printing output
println("list after group by is  ::")
println(group1)
}

Output:

integer by checking whether the element is divisible by '3' or not

Conclusion

Scala groupBy is used for grouping of elements based on some criteria defined as a predicate inside the function. This function internally converts the collection into map object and this map object work on key value pair. This is basically used for storing and retrieving of the elements. The main advantage of using groupBy in scala is that it can group by the elements based on condition or predicate we supply inside the function which can be used later in the program.

Recommended Articles

This is a guide to Scala groupBy. Here we discuss the introduction to Scala groupBy, how groupBy work along with programming examples. You may also have a look at the following articles to learn more –

  1. Scala Try Catch
  2. Scala Trait
  3. Scala foreach
  4. Scala Abstract Class

Scala Programming Training (3 Courses,1Project)

3 Online Courses

9+ Hours

Verifiable Certificate of Completion

Lifetime Validity

1 Project

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training (3 Courses,1Project) Learn More