0
0
Kotlinprogramming~3 mins

Why Sorted and sortedBy in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could sort any list with just one simple command, no matter how messy it is?

The Scenario

Imagine you have a messy list of your friends' names and ages, and you want to put them in order by age or alphabetically by name. Doing this by hand means writing lots of code to compare each friend one by one.

The Problem

Manually sorting means writing long, complicated code that is easy to get wrong. It takes a lot of time and effort, and if the list changes, you have to rewrite or fix your code again.

The Solution

Kotlin's sorted and sortedBy functions do the hard work for you. They quickly and safely arrange your list in the order you want with just one simple line of code.

Before vs After
Before
val sortedList = list.sortedWith(compareBy { it.age })
After
val sortedList = list.sortedBy { it.age }
What It Enables

You can easily organize data in any order you want, making your programs cleaner and faster to write.

Real Life Example

Sorting a list of products by price or sorting contacts by last name in a phone app becomes effortless and reliable.

Key Takeaways

Manual sorting is slow and error-prone.

sorted and sortedBy simplify sorting tasks.

They help you write cleaner and more readable code.