I have a Drink
object that has a property called strength
. Strength is an Integer with values of 0,1,2 or 3.
Now in my project, I display all of the Drink
objects in a List View. At the top of the list view, there's a filtering section for the user to filter the Drink
objects based on strength. These are CHECK BOXES, meaning users can select as little as 1 filter, or as much as 4. This gets saved to SharedPreferences as an Int Array.
data class Drink(val theDrinkName:String, val strength:Int)
object DrinkData {
const val low = 0
const val medium = 1
const val strong = 2
const val intense = 3
fun generateAllDrinks():Array<Drink> {
return arrayOf(
Drink("Vodka", medium),
Drink("Shirley Temple", low),
Drink("rum", strong),
Drink("Gin", medium),
Drink("151", intense),
Drink("99", strong)
)
}
}
Here's how I am generating all of the data:
val allDrinks = DrinkData.generateAllDrinks().sortedWith(
compareBy<Drink> { it.theDrinkName.first().isDigit() }
.thenBy { it.theDrinkName.toLowerCase() }
)
I need to be able to filter the strength property of this data based on an Int Array. (An Int Array is what gets saved to SharedPreferences.)
val filteredStrengthArray = arrayListOf<Int>(2,3)
This would filter allDrinks
to rum, 151, 99.
My progress:
This is the closet I got to achieving this filtering.
val allDrinks = DrinkData.generateAllDrinks().sortedWith(
compareBy<Drink> { it.theDrinkName.first().isDigit() }
.thenBy { it.theDrinkName.toLowerCase() }
).filter { it.strength == 2 || it.strength == 3 }
The problem is I need to filter by an Int Array to align what is saved in SharedPreferences.
How can I filter the strength property of this data by providing an Int Array?
CodePudding user response:
The first solution that comes to mind is checking if strength
property is contained by filteredStrengthArray
:
val filteredStrengthArray = arrayListOf<Int>(2,3)
val allDrinks = DrinkData.generateAllDrinks().sortedWith(
...
).filter { filteredStrengthArray.isEmpty() || filteredStrengthArray.contains(it.strength) }