Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i can iterate list to get 10 elements each time in java

Tags:

java

list

mysql

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...

like image 861
PSR Avatar asked Aug 05 '13 12:08

PSR


People also ask

How do you iterate through a list forEach?

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().

How do I traverse a list in Java 8?

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.

Can we use for-each loop for list in Java?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).


3 Answers

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 ...
}
like image 96
Marko Topolnik Avatar answered Oct 20 '22 00:10

Marko Topolnik


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.

like image 25
Craig P. Motlin Avatar answered Oct 19 '22 22:10

Craig P. Motlin


You can use the subList method in the List interface to divide your list.

like image 32
JHS Avatar answered Oct 19 '22 22:10

JHS