https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Mark

07/15/2020, 9:19 AM
Is there a flow operator to consolidate consecutive items under certain conditions? For example, suppose there is a flow of Strings and I want to concatenate consecutive single character strings like this: (‘a’, ‘bc’, ‘d’, ‘e’, ‘f’, ‘gh’) to (‘a’, ‘bc’, ‘def’, ‘gh’)
m

Michael de Kaste

07/15/2020, 3:20 PM
sorry, no. you can write one yourself using fold and rules
Copy code
val list = listOf("a", "bc", "d", "e", "f", "gh")
    
    val result = list.fold(mutableListOf<StringBuilder>() to false){ (list, buildingOnes), s ->
        list.apply {
            when{
                s.length == 1 && buildingOnes -> last().append(s)
                else -> add(StringBuilder(s))
            }
        } to (s.length == 1)
    }.first.map(StringBuilder::toString)

    result.forEach(::println)
👍 1