【问题标题】:How to filter a data class in Kotlin multiple times如何在 Kotlin 中多次过滤数据类
【发布时间】:2020-01-10 07:40:58
【问题描述】:

我想编写对我的数据类/对象列表执行过滤器的函数。我可以过滤类,但似乎每次想要再次过滤时我都需要创建一个新列表,有什么办法解决这个问题吗?

我创建了多个函数和扩展函数但它不起作用

我的数据类和自定义列表

data class Product(
    var name: String,
    var category: Category,
    var price: Double,
    var rating: Double
)

object ProductList {
    var productList = listOf(
        Product("Shopping Bag", Category.HOME, 11.75, 3.9),
        Product("Gold Earrings", Category.JEWELRY, 38.99, 4.2),
        Product("Golf Clubs", Category.SPORTS, 20.75, 4.1),
        Product("iPad", Category.ELECTRONICS, 180.75, 3.9),
        Product("MacBook Pro", Category.ELECTRONICS, 1200.85, 4.6),
        Product("Basketball Net", Category.SPORTS, 8.75, 3.5),
        Product("Lipstick", Category.WOMENS, 19.75, 4.1),
        Product("Dumbells", Category.HOME, 12.99, 4.8),
        Product("Gym Shoes", Category.MENS, 69.89, 3.9),
        Product("Coffee Mug", Category.HOME, 6.75, 3.9),
        Product("Reading Glasses", Category.MENS, 14.99, 2.8),
        Product("Nail Polish", Category.WOMENS, 8.50, 3.4),
        Product("Football Cleats", Category.SPORTS, 58.99, 3.9)
    )
}

我的两个过滤功能

fun filterByCategory(category: Category): List<Product> {
    return productList.filter { it.category == category }
}

fun filterByRating(productList: List<Product>,rating: Double): List<Product> {
    return productList.filter { it.rating >= rating }
}

我的排序功能

fun sortByPriceLowToHigh(productList: List<Product>) {
    val sortedByPrice = productList.sortedBy { it.price  }
    for (i in sortedByPrice) {
        println("${i.name}: ${i.price}")
    }

}


fun sortByPriceHighToLow(productList: List<Product>) {
    val sortedByPrice = productList.sortedByDescending { it.price }
    for (i in sortedByPrice) {
        println("${i.name}: ${i.price}")
    }

}

我的函数在主函数中调用

fun main(args: Array<String>) {

    val selectedCategory = filterByCategory(Category.HOME)
    filterByRating(selectedCategory, 4.0)
    println("Sorted by Price Low to High")
    sortByPriceLowToHigh(selectedCategory)
    println("")
    println("Sorted by Price High to Low")
    sortByPriceHighToLow(selectedCategory)

}

我希望我的输出按类别过滤此列表(它会)然后按评级再次过滤列表(它不会)

这是我的输出:

Sorted by Price Low to High
Coffee Mug: 6.75
Shopping Bag: 11.75
Dumbells: 12.99

Sorted by Price High to Low
Dumbells: 12.99
Shopping Bag: 11.75
Coffee Mug: 6.75

我想要的输出是:

Sorted by Price Low to High
Dumbells: 12.99

Sorted by Price High to Low
Dumbells: 12.99

因为哑铃是唯一一款评分高于 4.0 的产品,即 CATEGORY.HOME。 我知道我可以使用新谓词两次调用列表中的过滤器,但我想使用函数,以便可以在多个地方进行这些调用。

【问题讨论】:

  • 您没有使用函数返回的值。请注意,filter 不会修改原始列表,而是返回一个新的过滤列表。
  • 您能否检查我的答案并接受它是否适合您?

标签: android list kotlin filter collections


【解决方案1】:

正如m0skit0 所说:您应该使用filtersortedBy 等这些函数的返回值。

Kotlin 的集合 API 使用的是函数式方法,您无需修改​​传递给函数的值,而是返回结果。

我建议你在这种情况下使用扩展函数。链接它们看起来更好:

fun List<Product>.filterByCategory(category: Category) = this.filter { it.category == category }

fun List<Product>.filterByRating(rating: Double) = this.filter { it.rating >= rating }

fun List<Product>.sortByPriceLowToHigh() =
    this.sortedBy { it.price }
        .forEach { println("${it.name}: ${it.price}") }

fun List<Product>.sortByPriceHighToLow() =
    this.sortedByDescending { it.price }
        .forEach { println("${it.name}: ${it.price}") }

fun main() {
    val filteredProducts = ProductList.productList
        .filterByCategory(Category.HOME)
        .filterByRating(4.0)

    println("Sorted by Price Low to High")

    val lowToHighProducts = filteredProducts.sortByPriceLowToHigh()

    println("")
    println("Sorted by Price High to Low")

    val highToLowProducts = filteredProducts.sortByPriceHighToLow()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    相关资源
    最近更新 更多