2

I would like to determine the number of consecutive duplicate Strings in an ArrayList in Kotlin. What I have is something along the lines of:
val array: ArrayList<String> = arrayListOf("training", "training", "assessment", "training", "assessment", "assessment")

Where the output I want is something that counts the consecutive duplicate elements like:
[["training", "2"], ["assessment", "1"], ["training", "1"], ["assessment", "2"] or something simpler/cleaner.
I have found a similar solution in Python Counting consecutive duplicates of strings from a list. But I am looking for a Kotlin version. Thanks.

itcoder
  • 115
  • 9

1 Answers1

3

You could manually build the list, like this:

fun count(values: List<String>): List<Group> {
    val groups = mutableListOf<Group>()
    values.forEach {
        val last = groups.lastOrNull()
        if (last?.value == it) {
            last.count++
        } else {
            groups.add(Group(it, 1))
        }
    }
    return groups
}

data class Group(val value: String, var count: Int)

This results in:

[Group(value=training, count=2), Group(value=assessment, count=1), Group(value=training, count=1), Group(value=assessment, count=2)]
CampbellMG
  • 2,090
  • 1
  • 18
  • 27