Raymond Chenon
Raymond Chenon

Reputation: 12662

Kotlin map() reuse the same value

I have the following method

    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }

where l.split(" ") is called twice.

How to write in a smarter way in functional programming style ?

PS 1: I 'm curious for a solution with fold if possible

PS 2 : For readability, the original version was written as

 fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }

Upvotes: 0

Views: 199

Answers (3)

Rene
Rene

Reputation: 6148

Use map twice and combine it with destructuring:

val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String) =
    paragraph.split("\n").asSequence()
        .map { it.split(" ") }
        .map { (first, second) -> dateFormat.parse(first) to second }.toList()

Upvotes: 1

Cl&#233;ment Jean
Cl&#233;ment Jean

Reputation: 1916

I believe there is more functional and optimized way of writing this but here is a basic fold + with example:

val dateFormat = SimpleDateFormat("yyyy-MM-dd")

fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
   val lines = paragraph.split("\n")

    return lines.fold(listOf<Pair<Date, String>>()) { list, line -> 
        with (line.split(" ")) {
            list + Pair(dateFormat.parse(this[0]), this[1])
        }        
    }
}

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93619

This is a bit simpler. I don't see a way to use fold without making it way more convoluted.

val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> =
    paragraph.split("\n")
        .map { 
            with(it.split(" ")) { dateFormat.parse(this[0]) to this[1] }
        }

Upvotes: 2

Related Questions