Android:从多个 ArrayList 中插入一个 ArrayList 到 for() 循环中

问题描述 投票:0回答:1

我在 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);
            }
        }
    }
    ...
}
for-loop arraylist android-recyclerview
1个回答
0
投票

我不确定这是否是你的意思,但无论如何,就这样吧。
您只需首先确定要搜索哪个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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.