Updated April 7, 2023
Introduction to Kotlin groupBy
The kotlin groupby is one of the default function and it is used to perform the lambda operations and it returns the collection interface. The function groupby() is performed the key-value operations if we return the character as the array type it will return the group of characters. if suppose multiple keys are used to check and validate the specific conditions along with the groups and the elements are operated at one or more times by using the grouping instance it executes before the operation performed during the application grouping supports default functions to achieve these tasks.
Syntax
In kotlin standard libraries for implement the application with the help of collection elements and it is used to perform extensive functions. The grouping is one of the features for collecting the data items by using the specific category.
fun main(args:Array<String>)
{
val vars=listOf("") //listOf() is one of the array default method we can use our other default methods which based on the requirements.
vars.groupBy(parameters)
---some logic codes---
}
The above code is the basic syntax for performing the groupBy() function to perform the data operations on various areas.
How does groupBy works in Kotlin?
The groupby function is one of the built-in functions to perform the grouping operations with the specific data that can be achieved using the customized filters even though it can be applied in the data. Mostly the collection data and the util package is supported with these operations and other classes can also utilize these functionalities with the different areas. The collection package is mainly used for getting the results of lambda and corresponding values in the separated element list. It also called the value transformation function with the help of lambda expression. If we suppose the two lambda function is used, then it produced and called the key selector function which is mapped with separate values instead of the original elements. Grouping elements of the original array by the key it returns with the separate selector and it will be applied to the specific element returns with the collection interface like a map where as each key is associated with the list of corresponding values of the map interface in the view. The data are may be the list of strings, numbers, characters, operators, and symbols, etc and if want to group them with respect to their size, we can easily take and help the groupBy function which groups a collection based on the logic it provided and returns the map interface with that group of collections data.
Examples of Kotlin groupBy
Below are the different examples of Kotlin groupBy:
Example #1
Code:
package one;
class Test
{
fun demo(){
var lsts=ArrayList<String>()
lsts.add("Tamil is one of the language subject that relates to the history and known facts of the tamil peoples")
lsts.add("English is another language subject that also the international language which knows world facts")
lsts.add("Maths is one of the subject that relates to the mathematical concepts")
lsts.add("Computer science is one of the subject that relates to the computer language")
lsts.add("Physics is the subject that relates to the scientists and concepts relates to the research")
lsts.add("Chemistry is the subject that related to the chemical concepts and details")
lsts.add("Botany is the subject that describes about the natural plant like trees and leaves etc.")
lsts.add("Zoology is the subject it describes about the humans diseases and parts")
lsts.add("History is the subject that details about the historical concepts")
lsts.add("Geography is the subject that details about the earth and other planets")
for(i in lsts)
print("The arryList are iterated please find your input values $i ")
}
}
fun main(args: Array<String>) {
val vars = listOf("January is the first month", "February is the second month", "March is the third month", "April is the fourth month","May is the fifth month","June is the sixth month",
"July is the seventh month", "August is the eigth month", "September is the ninth month","October is the tenth month","November is the eleventh month","December is the tweleth month")
println(vars.groupBy { it.first().toUpperCase() })
println(vars.groupBy(keySelector = { it.first() },
valueTransform = { it.toUpperCase() }))
val lst = 1.rangeTo(17).toList()
println(lst.groupBy { it%5 })
val al=Test()
println(al.demo())
}
Output:
In the above example, we used a collection type called ArrayList class along with the groupby function on the code logic.
Example #2
Code:
package one;
enum class Cars(val available: Boolean = false){
maruthi(true),
jaquar,
benz,
ford,
swift,
toyota,
lancer(true),
rangerover,
volkswagen,
hyundai,
kia,
mahindra(true);
companion object{
fun custdet(modelname: Cars): Boolean {
return modelname.name.compareTo("July") == 0 || modelname.name.compareTo("January") == 0
}
}
}
class first
{
fun custdet(){
var custdetails=listOf("Sathyamoorthy street", "moorthy nagar", "chengalpattu district", "chennai")
println(custdetails.groupBy { it.first().toUpperCase() })
println(custdetails.groupBy(keySelector = { it.first() },
valueTransform = { it.toUpperCase() }))
println("Welcome To My Domain this is the second example regarding the kotlin groupby")
println("We have entered the customer details like customer id, customer name, customer salary, customer Address etc. the information’s are encrypted and it is stored in the separate database in cloud applications")
}
companion object Test{
var x: Int = 4
var custdetails=listOf("Sathyamoorthy street", "moorthy nagar", "chengalpattu district", "chennai")
fun custdet(){
println("Your details are: $x")
x++
}
fun custdeta(){
println("Welcome To My Domain this is the first example regarding the kotlin groupby concept")
println("${this.custdetails}")
println("the customer information’s are encrypted and it is stored in the sepaarte database in cloud applications")
}
}
}
fun main(args:Array<String>){
for(vars in Cars.values()) {
println("${vars.ordinal} = ${vars.name} the Cars equals ${vars.available}")
}
val details = Cars.benz;
println("Is details the month equals ${Cars.custdet(details)}")
first.custdet()
first.Test.custdet()
first.Test.custdeta()
println("Thank you users for spending the time with the companion object application")
}
Output:
In the second example, we used enums and companion objects for utilizing the customer details along with the groupby method for segregating the data.
Example #3
Code:
package one;
fun main(args: Array<String>) {
val fans = listOf("crompton", "havelles", "croma",
"bajaj", "usha", "butterfly")
println(fans.groupBy { it.first().toUpperCase() })
val tv = listOf("onida", "lg", "airtec",
"vu", "samsung", "sony")
println(tv.groupingBy { it.first() }.eachCount())
}
Output:
In the final example, we used both groupby and groupingBy methods differences for mapping the data and the time complexity of the codes.
Conclusion
The groupby is one of the util class and function for grouping the data from many forms to a single filter along with the input conditions. It has some default methods for performing the filter conditions and it also saves time-complexity, and performance and the user will see the data along with the specific conditions.
Recommended Articles
This is a guide to Kotlin groupBy. Here we discuss the introduction, syntax, and working of groupBy in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –