Angelina
Angelina

Reputation: 1573

Kotlin map values transformation - calculate sum inside the list and return map

I am trying to create a map of Hashtags and sum of corresponding transactions. I start with a list of transactions. Each can have several hashtags inside. In convertToSingleHashtagPerTransaction I extract each hashtag and add transactions to the list so that each transaction has only one hashtag. Then I group by hashtag and finally, I want to get rid of the Transaction object and get a map of String(hashtag), Double(sum of corresponding transactions).

val hashtagsAmountMap = transactions
            .filter { !it.note.isNullOrEmpty() }
            .filter { it.note!!.contains(HASHTAG_LEFT_SIDE) }
            .flatMap { convertToSingleHashtagPerTransaction(it) }
            .groupBy { it.note }
            .onEach {
                it.value
                        .map { it.inGlobalCurrency!! }
                        .sumByDouble { it }
            }

private fun convertToSingleHashtagPerTransaction(t: Transaction): List<Transaction> {
    val note = t.note
    if (note != null) {
        return extractHashtags(note)
                .map {
                    t.copy(note = it.toUpperCase())
                }
    } else {
        return arrayListOf()
    }
}

In the end I keep getting List instead of List.

Upvotes: 1

Views: 2625

Answers (1)

Angelina
Angelina

Reputation: 1573

As soon as I posted a question to StackOverflow, I figured out the answer myself:

val hashtagsAmountMap = transactions
            .filter { !it.note.isNullOrEmpty() }
            .filter { it.note!!.contains(HASHTAG_LEFT_SIDE) }
            .flatMap { convertToSingleHashtagPerTransaction(it) }
            .groupBy { it.note }
            .mapValues { entry ->
                entry.value
                        .map { it.amountGlobalCurrency!! }
                        .sum()
            }

Upvotes: 4

Related Questions