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.

1 Answer 1

2

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)]
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I am looking for, thanks @CampbellMG! Made my whole function a lot cleaner :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.