Skip to Content
Course content

82: List Operations: map, filter, fold In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're running a small warehouse. You have a giant conveyor belt carrying a mix of random items. Now, you don't want everything on that belt; you only want the electronics. Once you've picked those out, you want to put a protective foam wrap around each one. Finally, you want to know the total weight of all those wrapped electronics so you can book the right size shipping container.

That's exactly what filter, map, and fold do to your data. filter is your quality control—it keeps only what fits the criteria. map is your processing station—it changes every item in the list into something else. And fold is your final tally—it takes a whole list of things and collapses them down into one single value.

Sifting the Noise with Filter

I see a lot of developers write for loops with an if statement inside just to build a new list. Please, don't do that. It's noisy. In Kotlin, we use filter. It takes a predicate—basically a function that returns true or false—and returns a new list containing only the items that passed the test.

data class Product(val name: String, val price: Double, val category: String)

val inventory = listOf(
    Product("Laptop", 1200.0, "Electronics"),
    Product("Apple", 1.0, "Food"),
    Product("Smartphone", 800.0, "Electronics"),
    Product("Bread", 2.5, "Food")
)

// I only want the electronics
val electronics = inventory.filter { it.category == "Electronics" }
// Result: [Product(Laptop, 1200.0, Electronics), Product(Smartphone, 800.0, Electronics)]

Transforming the Results with Map

Once you have your filtered list, you often need to change the format of the data. Maybe you don't need the whole Product object anymore; maybe you just need a list of the prices to send to a payment gateway. That's where map comes in. It transforms every single element in the list using the logic you provide.

The key thing to remember here is that map can change the type of the list. We can go from a List<Product> to a List<Double> effortlessly.

// Now, let's just get the prices of those electronics
val prices = electronics.map { it.price }
// Result: [1200.0, 800.0]

Collapsing the List with Fold

This is where things get interesting. fold is the Swiss Army knife of list operations. While map and filter return another list, fold returns a single value. It does this by carrying an "accumulator" along as it traverses the list.

Think of it like a snowball rolling down a hill. You start with an initial value (the small snowball), and as it hits each element in the list, it adds to itself based on your logic.

// Let's calculate the total value of electronics, starting from 0.0
val totalValue = electronics.fold(0.0) { accumulator, product -> 
    accumulator + product.price 
}
// Result: 2000.0

I'll be honest: fold can look intimidating at first because of the accumulator. But once you realize it's just a way to "reduce" a list into one result, it becomes your best friend. In the example above, 0.0 is the starting point. For the first product, accumulator is 0.0 and product.price is 1200.0. The result (1200.0) then becomes the accumulator for the next item.

Chaining it All Together

The real power happens when you chain these. Instead of creating intermediate variables like electronics and prices, you can pipe the data through a transformation pipeline. This is where Kotlin code starts to look really clean and expressive.

val grandTotal = inventory
    .filter { it.category == "Electronics" }
    .map { it.price * 1.10 } // Adding 10% tax to each item
    .fold(0.0) { acc, price -> acc + price }

println("Total with tax: $grandTotal")

Just a heads-up: be mindful of performance on massive lists. Every time you call filter or map, Kotlin creates a new list in memory. If you're dealing with millions of items, look into asSequence() to make this "lazy," but for most day-to-day apps, chaining is the way to go.




📋 Practical Task

Exercise: The VIP Customer Revenue Calculator

You are building a reporting tool for a subscription service. You have a list of User objects. Your goal is to calculate the total revenue generated only from users who have a "Premium" status and have been members for more than 1 year.

The Requirements:

  • Start with the provided list of users.
  • Filter out anyone who is NOT "Premium".
  • Filter out anyone whose tenureYears is 1 or less.
  • Map the remaining users to their monthlyFee.
  • Use fold to sum these fees into a total monthly revenue value.
data class User(val name: String, val status: String, val tenureYears: Int, val monthlyFee: Double)

val users = listOf(
    User("Alice", "Premium", 2, 29.99),
    User("Bob", "Free", 3, 0.0),
    User("Charlie", "Premium", 1, 29.99),
    User("Diana", "Premium", 5, 49.99),
    User("Eve", "Free", 1, 0.0)
)

fun main() {
    // Your code here: 
    // Chain filter, map, and fold to calculate the total revenue for eligible VIPs.
    // Expected Result: 79.98 (Alice + Diana)
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.