Now, let's combine projection, filtering, and aggregation to see the collective power of these techniques. We'll extend our example to demonstrate this flow:
- Data Projection: Choose only the desired fields.
- Data Filtering: Filter the data based on certain conditions.
- Data Aggregation: Summarize the filtered data.
We'll modify our DataStream class to include all the methods and then use them together in a workflow. The projection and filtering methods will now return an instance of DataStream, not a list as before, so that we can chain these methods when calling them:
class DataStream(private val data: List<Map<String, Any?>>) {
fun projectData(keys: List<String>): DataStream {
val projectedData = data.map { entry ->
entry.filterKeys { it in keys }
}
return DataStream(projectedData)
}
fun filterData(predicate: (Map<String, Any?>) -> Boolean): DataStream {
val filteredData = data.filter(predicate)
return DataStream(filteredData)
}
fun aggregateData(key: String, aggFunc: (List<Int>) -> Double): Double {
val values = data.mapNotNull { it[key] as? Int }
return aggFunc(values)
}
}
fun main() {
// Example usage
val ds = DataStream(
listOf(
mapOf("name" to "Alice", "age" to 25, "profession" to "Engineer", "salary" to 70000),
mapOf("name" to "Bob", "age" to 30, "profession" to "Doctor", "salary" to 120000),
mapOf("name" to "Carol", "age" to 35, "profession" to "Artist", "salary" to 50000),
mapOf("name" to "David", "age" to 40, "profession" to "Engineer", "salary" to 90000)
)
)
// Step 1: Project the data to include only 'name', 'age', and 'salary'
val projectedDs = ds.projectData(listOf("name", "age", "salary"))
// Step 2: Filter the projected data to include only those with age > 30
val filteredDs = projectedDs.filterData { it["age"] as Int > 30 }
// Step 3: Aggregate the filtered data to compute the average salary
val averageSalary = filteredDs.aggregateData("salary") { salaries -> salaries.average() }
println(averageSalary) // Outputs: 70000.0
}
Here:
- Projection: We choose only the
name, age, and salary fields from our data. The projectData method now returns a DataStream object, allowing us to chain multiple operations.
- Filtering: We filter the projected data to include only those persons whose age is greater than 30. The
filterData method also returns a DataStream object for chaining.
- Aggregation: We calculate the average salary of the filtered data. The final output shows the average salary for those aged over 30, which is
70,000.
By combining these methods, our data manipulation becomes both powerful and concise. Try experimenting and see what you can create!