java - 基于索引迭代列表
问题描述
我有一个ArrayList
并且我正在迭代列表以构建查询,但我的查询只能有 20,000 个字符,所以我试图迭代某些索引,以便我可以有多个查询。我该怎么做?任何指导都会有所帮助。
for(int i=0; i < EntryList.size(); i++){
String entryValue = (String) EntryList.get(i);
Query = Query + entryValue;
}
假设我的列表有 500 个项目,我想遍历每 100 或 200 个项目以获取我的查询。
解决方案
您可以通过创建一个单独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));
}
推荐阅读
- python-3.x - 在 Oracle Linux 6.9 中已安装 Python3.5.5 但未打开
- javascript - “if”和“else if”条件都在过滤器函数中执行(Angular-8,JavaScript)
- arrays - 比较数组条目
- ios - WKWebView 在 iOS 9 上以 30M 的 RAM 使用率崩溃
- delphi - 如何在 Delphi 中使用通配符搜索注册表
- c++ - 在流 c++ 的文本之前有一个额外的换行符
- reactjs - 使用recharts的多系列数据条形图问题
- bootstrap-4 - 引导选择 optgroup 映像
- amazon-web-services - 使用 sha1 进行 AWS S3 签名实际上安全吗?
- amazon-web-services - 我应该选择什么 Elastic Beanstalk 环境?