Examples · Kotlin

Parse CSV in Kotlin and see it as a table

For a quick look at some CSV you don't need a library: split the lines, destructure the fields into a data class, and the standard library does the rest.

Here five sales rows become Sale objects with a computed revenue, and the revenue is totalled per region. Both show as tables.

The query

kotlin-parse-csv.kts · paste it into a Kotlin tab and press F5, or run byterunner run kotlin-parse-csv.kts in a terminal

// Turn CSV text into objects, then look at it as a table. For a file, the same works on
// java.io.File("sales.csv").readText()
val csv = """
    region,product,units,price
    North,Widget,120,2.50
    South,Widget,80,2.50
    North,Gadget,15,19.99
    West,Gadget,42,19.99
    South,Gizmo,7,149.00
""".trimIndent()

data class Sale(val region: String, val product: String, val units: Int, val price: Double) {
    val revenue get() = units * price
}

val sales = csv.lines().drop(1).map { line ->
    val (region, product, units, price) = line.split(",")
    Sale(region, product, units.toInt(), price.toDouble())
}
sales.dump("Sales")

sales.groupBy { it.region }
    .mapValues { (_, rows) -> "%.2f".format(rows.sumOf { it.revenue }) }
    .toSortedMap()
    .dump("Revenue per region")

What it shows

The output of that run, from byterunner run. In the app each table is a sortable grid.

Sales
region  product  units  price
------  -------  -----  -----
North   Widget   120    2.5
South   Widget   80     2.5
North   Gadget   15     19.99
West    Gadget   42     19.99
South   Gizmo    7      149.0
(5 rows)
Revenue per region
Key    Value
-----  -------
North  599.85
South  1243.00
West   839.58
(3 rows)

To read a file, use java.io.File("sales.csv").readText() in place of the text in the query. Quoted fields with commas in them need a real CSV parser; one can be pulled in from Maven Central with @file:DependsOn, as in the Maven example.

A computed property such as revenue is a column in the table like any other.

Download ByteRunner Free for Windows and Linux. Getting started

More examples