I have a filter method in MainActivity
for two ArrayList
s, smallList
and mainList
.
How can I write for()
loop code to select one of the lists based on the criteria shown, so that I don't have to use two for()
loops?
private void filter(String searchText) {
ArrayList<Card> searchList = new ArrayList<>();
// Determine which RecyclerView list to use and then run a for() loop that
// searches the database for input search text.
if (smallList != null && !smallList.isEmpty()) {
for (Card cardItem : **smallList**) {
if (cardItem.getInfo().contains(searchText)) {
searchList.add(cardItem);
}
}
}
else {
for (Card cardItem : **mainList**) {
if (cardItem.getInfo().contains(searchText)) {
searchList.add(cardItem);
}
}
}
...
}
I'm not sure if this is what you mean, but anyway, here goes.
You simply first determine which List you want to search. Then you search only that List
. Hence single for
loop.
java.util.List<Card> list = smallList != null && !smallList.isEmpty() ? smallList : mainList;
for (Card cardItem : list) {
if (cardItem.getInfo().contains(searchText)) {
searchList.add(cardItem);
}
}