You can do this by creating a separate List
to hold each individual query that adheres to your length limit.
Then we just iterate over your list of entries and build each query. Once the query reaches your maximum length, add it to the queriesList
and start over on building a new query.
Your question isn't incredibly clear on your requirements or the end goal, but here is a simple MCVE to demonstrate.
It will build queries up to 100 characters in length.
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);
}
}
}
If, however, you do want to have a specific number of entries in each query (instead of number of characters per query), you can reset the StringBuilder
after every 100-200 items:
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));
}