I have a list with 70 elements.
For Example:
List<Long> dbList = new ArrayList<Long>();
dbList
has 70 records. If I send all the records to a query in MySql it takes a long time. So now I want to send each time 10 elements to database query. So I need to iterate over the list in intervals of 10. How can I do this? Is this a good approach to avoid long time when using IN
.
SQL Query
select model.boothId, model.panchayat.panchayatId
from Table1 model
where model.panchayat.panchayatId in(:locationValues)
and model.publicationDate.publicationDateId in (:publicationDateIdsList)
and model.constituency.id = :id group by model.panchayat.panchayatId
Thanks in advance...
Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. Within the loop, obtain each element by calling next().
Since Java 8, we can use the forEach() method to iterate over the elements of a list. This method is defined in the Iterable interface, and can accept Lambda expressions as a parameter.
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
ArrayList#subList
is a very efficient operation. You can iterate over ranges of size 10:
for (int i = 0; i < dbList.size(); i += 10) {
List<Long> sub = dbList.subList(i, Math.min(dbList.size(),i+10)));
... query ...
}
If you use Eclipse Collections (formerly GS Collections) and change dbList to a MutableList or something similar, you can write:
MutableList<Long> dbList = ...;
RichIterable<RichIterable<Long>> chunks = dbList.chunk(10);
If you can't change the return type of dbList, you can wrap it in a ListAdapter.
RichIterable<RichIterable<Long>> chunks = ListAdapter.adapt(dbList).chunk(10);
Note: I am a committer for Eclipse Collections.
You can use the subList
method in the List
interface to divide your list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With