Updated June 30, 2023
Introduction to Scala groupBy
Scala groupBy is part of the collection data structure. As the name suggests, it is used to group the elements of collections. This groupBy is applicable for both mutable and immutable collections 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 so we can perform some useful operations on it. It will return us a map that will contain the key-value pair.
Syntax and parameters:
Scala groupBy function takes a predicate as a parameter, and based on this, it groups 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 will return a map of the 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 a 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 and how it is working:
someList.groupBy(obj => obj)
In the above line, we can see some list names followed by the groupBy function, and inside the groupBy function, there is one anonymous function (=>); this function will iterate over all the list elements and group the element which has the same value as ‘obj.’ After that, internally, it will convert that into HashMap with a key-value pair and all the elements with the same content into one group. If two or more elements are the same inside the list, then they will map against the same key inside the HashMap.
Let’s have a look at its extended superclasses 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
Superclasses 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, we first defined a list containing some objects. This list also contains some duplicate objects as well. After that, we are applying the groupBy function to group by the same elements. So in our list vinit and Lalit, it appears to be more than one time, so while creating HashMap, it will group all these similar list elements against the same key in the map.
This is something weird, but it is helpful if we want to apply some logic on the 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 a 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 on the basis of contains method as a 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 a 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 grouped by the list of integers 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 elements based on some criteria defined as a predicate inside the function. This function internally converts the collection into a map object, and this map object works on key-value pair. This is basically used for storing and retrieving the elements. The main advantage of using groupBy in scala is that it can group by the elements based on the condition or predicate we supply inside the function, which can be used later in the program.
Recommended Articles
We hope that this EDUCBA information on “Scala groupBy” was beneficial to you. You can view EDUCBA’s recommended articles for more information.