Grouping and Sorting
groupBy and sortBy.
Grouping and Sorting is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit. This is lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, and your progress syncs across the web and the CoddyKit app. The Scala for Backend Engineering & Functional Programming course includes 4 lessons in total.
Organizing data
Real-world data often needs to be grouped by a property or sorted by a key. Scala collections offer groupBy, sortBy, sortWith, and friends to do this declaratively.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(5, 3, 8, 1, 9, 2)
println(nums.sorted)
}
}sorted: natural order
sorted sorts elements in their natural order (ascending for numbers, alphabetical for strings). It needs an ordering, which exists for common types.
object Main {
def main(args: Array[String]): Unit = {
println(List(3, 1, 2).sorted)
println(List("pear", "apple", "fig").sorted)
}
}sortBy: sort by a key
sortBy sorts by a value derived from each element. Provide a function that extracts the sort key.
object Main {
def main(args: Array[String]): Unit = {
val words = List("banana", "fig", "apple")
val byLength = words.sortBy(_.length)
println(byLength)
}
}Sorting in descending order
To sort descending, negate a numeric key or use sorted(Ordering.Int.reverse). For derived keys, sortBy with a minus sign is concise.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(5, 3, 8, 1)
println(nums.sortBy(-_))
println(nums.sorted(Ordering.Int.reverse))
}
}sortWith: custom comparator
sortWith takes a function returning true when the first argument should come before the second, giving you full control over ordering.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(5, 3, 8, 1)
val descending = nums.sortWith((a, b) => a > b)
println(descending)
}
}Sorting by multiple keys
sortBy can return a tuple to sort by several keys at once: it compares the first element, then the second to break ties.
object Main {
def main(args: Array[String]): Unit = {
val people = List(("Ann", 30), ("Bob", 25), ("Ann", 22))
val sorted = people.sortBy { case (name, age) => (name, age) }
println(sorted)
}
}groupBy: partition into a Map
groupBy returns a Map where each key is the result of your function and each value is the list of elements sharing that key.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6)
val byParity = nums.groupBy(_ % 2 == 0)
println(byParity)
}
}Grouping by a computed key
The grouping key can be anything: a first letter, a length, a category. Each distinct key becomes a bucket.
object Main {
def main(args: Array[String]): Unit = {
val words = List("apple", "avocado", "banana", "cherry", "cranberry")
val byFirstLetter = words.groupBy(_.head)
byFirstLetter.foreach { case (letter, ws) => println(s"$letter -> $ws") }
}
}Transforming groups
After grouping, you often want to summarize each bucket. Use view.mapValues (or map) to transform the values, for example counting elements per group.
object Main {
def main(args: Array[String]): Unit = {
val words = List("cat", "car", "dog", "deer", "cow")
val counts = words.groupBy(_.head).view.mapValues(_.size).toMap
println(counts)
}
}groupMapReduce in one step
groupMapReduce groups, maps each element, and reduces each group's values, all in a single pass. It is a concise way to build summaries like sums per category.
object Main {
def main(args: Array[String]): Unit = {
val sales = List(("books", 10), ("toys", 5), ("books", 7), ("toys", 3))
val totals = sales.groupMapReduce(_._1)(_._2)(_ + _)
println(totals)
}
}Combining group and sort
A frequent pattern: group data, summarize each group, then sort the summary. Here we count words per first letter and sort by count.
object Main {
def main(args: Array[String]): Unit = {
val words = List("apple", "avocado", "banana", "cherry", "cranberry", "apricot")
val ranked = words
.groupBy(_.head)
.view.mapValues(_.size).toList
.sortBy(-_._2)
println(ranked)
}
}Quick Check
What does List(1,2,3,4).groupBy(_ % 2 == 0) return?
Recap
You learned grouping and sorting:
sorted— natural ordersortBy— sort by a derived key (tuple for multi-key)sortWith— custom comparatorgroupBy— partition into aMapof bucketsgroupMapReduce— group, map, and reduce in one pass
Frequently Asked Questions
Is the “Grouping and Sorting” lesson free?
Yes — the full text of “Grouping and Sorting” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO. The Scala for Backend Engineering & Functional Programming course includes 4 lessons in total.
What will I learn in “Grouping and Sorting”?
groupBy and sortBy. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
How long does the “Grouping and Sorting” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- List, Vector, Set, Map
- Transformations
- Folding and Reducing
- Grouping and Sorting