article banner

Exercise: Crime analysis

Your task is to analyze crime data from Chicago in order to count the number of crimes per primary cause. You’ve implemented the solution, but it fails due to OutOfMemoryError. Fix it.

fun main() { measureTimeMillis { File("Crimes_-_2001_to_Present.csv") .readLines() .drop(1) .map { Crime.parse(it) } .groupBy { it.primaryType } .mapValues { it.value.size } .toList() .sortedByDescending { (_, num) -> num } .joinToString(separator = "\n") { (type, num) -> "$num $type" } .let(::println) }.let { println("Took $it") } }

Download data in CSV format from the following link:

Compare execution time of the following solutions that use the groupBy function to group elements, and the same solutions that use groupingBy function to group elements.

Once you are done with the exercise, you can check your solution here.