Topic Overview and Importance

Hello and welcome! Today, we're exploring practical data manipulation techniques in Kotlin. We'll use Kotlin List collections to represent our data stream and perform projection, filtering, and aggregation. And here's the star of the show: our operations will be neatly packaged within a Kotlin class! No mess, all clean code.

Introduction to Data Manipulation

Data manipulation is akin to being a sculptor but for data. We chisel and shape our data to get the desired structure. Kotlin lists are perfect for this, and our operations will be conveniently bundled inside a Kotlin class. So, let's get our toolbox ready! Here's a simple Kotlin class, DataStream, that will serve as our toolbox:

Kotlin
class DataStream(private val data: List<Map<String, Any?>>)
Data Projection in Practice
Data Filtering in Practice

Next, we have data filtering, which is like cherry-picking our preferred data entries. We'll extend our DataStream class with a filterData method that uses a "predicate" function to filter data:

class DataStream(private val data: List<Map<String, Any?>>) {
    
    // ... other methods ...

    fun filterData(predicate: (Map<String, Any?>) -> Boolean): DataStream {
        val filteredData = data.filter(predicate)
        return DataStream(filteredData)
    }
}

fun main() {
    // Applying it:
    val ds = DataStream(
        listOf(
            mapOf("name" to "Alice", "age" to 25, "profession" to "Engineer"),
            mapOf("name" to "Bob", "age" to 30, "profession" to "Doctor")
        )
    )
    val ageTest: (Map<String, Any?>) -> Boolean = { it["age"] as Int > 26 }
    val filteredDs = ds.filterData(ageTest)
    println(filteredDs.dataToString())  // Outputs: [{name=Bob, age=30, profession=Doctor}]
}

With the filter method, our output is a list with only Bob’s data, as he's the only one who passes the "age over 26" test.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal