我在 MainActivity 中有一个过滤方法,用于两个 ArrayList、smallList 和 mainList。
如何编写 for() 循环代码来根据显示的条件选择列表之一,这样我就不必使用两个 for() 循环?
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);
}
}
}
...
}
我不确定这是否是你的意思,但无论如何,就这样吧。
您只需首先确定要搜索哪个List。然后你只搜索那个
List
。因此单个 for
循环。
java.util.List<Card> list = smallList != null && !smallList.isEmpty() ? smallList : mainList;
for (Card cardItem : smallList) {
if (cardItem.getInfo().contains(searchText)) {
searchList.add(cardItem);
}
}