fun main(args: Array) { untangle(java.io.StringReader(""" 1 hello 2 the world is so nice 1 bye """.trimIndent())).forEach { println(it) } } fun untangle(reader: java.io.Reader): Collection { val pattern = Regex("""(\d+) .+""") val writers = mutableMapOf() var current: StringBuilder? = null // reader.forEachLine { line -> for (line in reader.readLines()) { val matchResult = pattern.matchEntire(line) if (matchResult != null) { val id = matchResult.groupValues[1] current = writers[id] if (current == null) { current = StringBuilder() writers[id] = current } current.appendln(line) } else if (current != null) { current.appendln(line) } } return writers.values }