【发布时间】: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