根据索引遍历列表

时间:2018-11-01 20:24:27

标签: java

我有一个ArrayList,我正在遍历列表以构建查询,但是我的查询只能包含20,000个字符,因此我尝试遍历某些索引,因此可以有多个查询。我该怎么做?任何指导都会有所帮助。

for(int i=0; i < EntryList.size(); i++){

    String entryValue = (String) EntryList.get(i);

    Query = Query + entryValue;
}

说我的列表有500个项目,我想每100或200个项目进行迭代以获取查询。

1 个答案:

答案 0 :(得分:0)

您可以通过创建一个单独的List来容纳符合您的长度限制的每个查询来做到这一点。

然后,我们仅遍历您的条目列表并构建每个查询。查询达到最大长度后,将其添加到queriesList并重新开始构建新查询。

您的问题在您的要求或最终目标上并不清楚,但是这里有一个简单的MCVE可以演示。

它将建立最长100个字符的查询。

import java.util.ArrayList;
import java.util.List;

class Scratch {
    public static void main(String[] args) {

        // Create a sample list of entries, with 50 items
        List<String> entryList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            entryList.add("Entry" + i);
        }

        // Create a list to hold our list of queries that are all under the maximum length
        List<String> queriesList = new ArrayList<>();
        int maxQueryLength = 100;

        // Create a new StringBuilder to add our entries to
        StringBuilder tempQuery = new StringBuilder();

        // Loop through all entries and build a query, up to the max characters
        for (String entry : entryList) {

            // Check the length of the current query
            if (tempQuery.length() + entry.length() > maxQueryLength) {
                // Add the tempQuery to our list of queries and start fresh
                queriesList.add(tempQuery.toString());
                tempQuery.setLength(0);
            }

            tempQuery.append(entry);
        }

        // We now have our list of separate queries that we can run individually
        for (String query : queriesList) {
            System.out.println(query);
        }

    }
}

但是,如果您确实希望每个查询中都有特定的数量个条目(而不是每个查询的字符数),则可以在每100个字符后重置StringBuilder 200个项目:

    for (int i = 0; i < entryList.size(); i++) {

        // If this iteration is a multiple of 100, start a new query, otherwise just add to it
        if ((i + 1) % 100 == 0) {   // We add 1 to i here to avoid adding an empty query on the first pass
            // Add the tempQuery to our list of queries and start fresh
            queriesList.add(tempQuery.toString());
            tempQuery.setLength(0);
        }

        tempQuery.append(entryList.get(i));
    }