首页 > 解决方案 > 基于索引迭代列表

问题描述

我有一个ArrayList并且我正在迭代列表以构建查询,但我的查询只能有 20,000 个字符,所以我试图迭代某些索引,以便我可以有多个查询。我该怎么做?任何指导都会有所帮助。

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

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

    Query = Query + entryValue;
}

假设我的列表有 500 个项目,我想遍历每 100 或 200 个项目以获取我的查询。

标签: java

解决方案


您可以通过创建一个单独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);
        }

    }
}

但是,如果您确实希望在每个查询中有特定数量的条目(而不是每个查询的字符数),您可以StringBuilder在每 100-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));
    }

推荐阅读