javadictionarykotlin

How to groupBy and remove repeated objects


I have this Item class:

data class Product(val id: Long, val name: String, val region: Long)

Given a list List<Product>:

Product(1, "Product 1", 1)
Product(1, "Product 1", 1)
Product(1, "Product 1", 2)
Product(2, "Product 2", 1)

As you can see the same product can be added many times to same Region. I want to groupBy region like productList.groupBy { it.region } but in the generated map entries I want to remove the products that has the same Id.


Solution

  • productList.groupBy { it.region }.mapValues { it.value.distinctBy { it.id } }
    

    mapValues:

    Returns a new map with entries having the keys of this map and the values obtained by applying the transform function to each entry in this Map.

    distinctBy:

    Returns a list containing only elements from the given collection having distinct keys returned by the given selector function.