gpt4 book ai didi

java - 如何分组并删除重复的对象

转载 作者:行者123 更新时间:2023-12-01 19:32:16 24 4
gpt4 key购买 nike

我有这个 Item 类:

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

给定一个列表List<Product> :

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

如您所见,同一产品可以多次添加到同一区域。我想按区域分组 productList.groupBy { it.region }但在生成的 map 条目中,我想删除具有相同 ID 的产品。

最佳答案

productList.groupBy { it.region }.mapValues { it.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.

关于java - 如何分组并删除重复的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59261102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com