Kotlin:如何检查 mutabeListOf<Pair<Object, Int>> 是否已包含特定对象?

Kotlin: How to check if a mutabeListOf<Pair<Object, Int>> already contains a specific Object?

我想检查 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")
}

输出应该是:

Productname: Test, 6

而不是:

Productname: Test, 1

Productname: Test, 5

这里是产品 Class:

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

和项目 Class:

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

目前,没有任何效果(无论是比较还是添加新的对)。我感谢每一个 post!

根据您的需要,这里有两种可能。

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 class 成为 data class(或手动实施 equalshashcode)以便能够进行比较使用它们的 productName 值的两个 Product 的散列。

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
}