GettingStarted
GettingStarted

Reputation: 7605

Kotlin finding duplicate items in mutableList

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?

Upvotes: 1

Views: 4987

Answers (1)

Iaroslav Postovalov
Iaroslav Postovalov

Reputation: 2453

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}.

Upvotes: 6

Related Questions