Kotlin finding duplicate items in mutableList

4.3k Views Asked by At

I have a List

 val shoeCart = ShoeRepository.getShoeFromCart(this@ActivityCart)

from ShoeRepository

 fun getShoeFromCart(context: Context): List<ShoeModel> {
    return getCart(context)
}

ShoeModel is a data class

data class ShoeModel

I want to find out if my shoeCart has duplicate entries in it, and if it does, how many?

1

There are 1 best solutions below

0
On BEST ANSWER

Data classes have their equals method implemented, so we can use eachCount Map extension to map values to their quantities.

data class ShoeModel(val someProperty: Int)

fun main() {
    val source = listOf(ShoeModel(1), ShoeModel(2), ShoeModel(1), ShoeModel(2), ShoeModel(3))
    println(source.groupingBy { it }.eachCount().filter { (_, v) -> v >= 2 })
}

The output of this snippet is {ShoeModel(someProperty=1)=2, ShoeModel(someProperty=2)=2}.