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:
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:
4.5 (5,543 ratings)
View Course
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:
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:
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:
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:
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:
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 –