Kotlin:如何检查mutabeListOf >是否已包含特定对象?

问题描述 投票:0回答:1

我想检查mutableListOf<Pair<Product, Int>>是否已经包含具有特定名称的产品。如果搜索到的名称带有Pair<Product, Int>,则应增加此产品的Int值。

这是我的方法:

fun main() {
    val item = Item()

    val prod1 = Product("Test")
    val prod2 = Product("Test")

    item.addProduct(prod1, 1)
    item.addProduct(prod2, 5)

   for ((prod,amount) in item) println("$Productname: {prod.productName}, $amount")
}

输出应为:

产品名称:测试,6

而不是:

产品名称:测试,1

产品名称:测试,5

这里是产品类别:

class Product(val productName: String) {
    // other stuff that is unnecessary for the question
}

和物品类别:

class Item {
    private val pairList = mutableListOf<Pair<Product, Int>>()

    fun addProduct(product: Product, quantity: Int) {
        for (prod in pairList) {
            if (pairList.contains(Pair(product, quantity))){
                val value = prod.second + quantity
                prod.copy(second = value)
            } else {
                pairList.add(Pair(product, quantity))
            }
        }
    }
}

目前,没有任何效果(比较或添加新对都无效)。我感谢每个帖子!

list kotlin comparison
1个回答
0
投票

这里有两种可能,取决于您的需求。

1。使用MutableMap<Product, Int>

这是使用MutableMap<K, V>而不是MutableList<Pair<K, V>>的完美用例,因为您需要找到给定产品的当前数量并增加它的数量:

private val productMap = mutableMapOf<Product, Int>()

fun addProduct(product: Product, quantity: Int) {
    val foundQuantity = productMap[product]
    // Increase the found quantity by [quantity] or add the given [quantity].
    val finalQuantity = foundQuantity?.let { it + quantity } ?: quantity
    productMap[product] = finalQuantity
}

为此,您应将Product类设为data class(或手动实现equalshashcode),以便能够使用它们的Product值比较两个productName的哈希值。

data class Product(val productName: String) { ... }

此解决方案的优点是快速查找和快速插入。此解决方案的缺点是您的产品将不再分类。

2。使用MutableList<Pair<Product, Int>>

如果您需要对产品进行排序,并且需要保持相同的插入顺序,那么您仍然可以使用列表进行一些优化。

private val pairList = mutableListOf<Pair<Product, Int>>()

fun addProduct(product: Product, quantity: Int) {
    pairList.forEachIndexed { index, (savedProduct, savedQuantity) ->
        if (savedProduct.productName == product.productName) {
            // This is the product we are searching for.
            pairList[index] = product to quantity + savedQuantity
            // We found the product and replaced it, we don't need to search for it anymore.
            return
        }
    }
    // We didn't find a product, add it as the last item.
    pairList += product to quantity
}
© www.soinside.com 2019 - 2024. All rights reserved.