我如何迭代列表以在java中每次获得10个元素

我有一个包含70个元素的列表。

例如:

List dbList = new ArrayList();

dbList有70条记录。 如果我将所有记录发送到MySql中的查询,则需要很长时间。 所以现在我想每次向数据库查询发送10个元素。 所以我需要以10为间隔迭代列表。我该怎么做? 这是避免长时间使用IN的好方法。

SQL查询

 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 

提前致谢…

ArrayList#subList是一种非常有效的操作。 您可以迭代大小为10的范围:

 for (int i = 0; i < dbList.size(); i += 10) { List sub = dbList.subList(i, Math.min(dbList.size(),i+10))); ... query ... } 

如果您使用Eclipse Collections (以前称为GS Collections )并将dbList更改为MutableList或类似的东西,您可以编写:

 MutableList dbList = ...; RichIterable> chunks = dbList.chunk(10); 

如果无法更改dbList的返回类型,则可以将其包装在ListAdapter中。

 RichIterable> chunks = ListAdapter.adapt(dbList).chunk(10); 

注意:我是Eclipse Collections的提交者。

您可以使用List接口中的subList方法来划分列表。

我不确切地知道你想要做什么,但你可以尝试类似下面的伪代码,如果你用循环构建你的查询:

 counter=0; for (Long item : dbList){ query.add (item); if (counter>10){ query.send(); counter=0; } } if (!query.empty()) query.send(); 

这只是伪代码。 可能你没有像这样的查询对象,但只是为了解释我的观点。

希望能帮助到你

在纯Java代码中,它可能可以完成:

 int parts = list.size()/10; for(int i=0; i<10; i++){ for(int j=0; j 

正如d’alar’cop所说,我认为这可能与您的SQL语句有关,而不是列表。 但无论如何,我会做这样的事情:

 int i = 1; List newList = new ArrayList(); for(Long item : dbList) { for (i <= 10; i++) { newList.Add(item) if (i == 10) { //SQL Statement i = 1; } break; } } 

或者,其他人提到的子列表也可以使用,也可以是更紧凑的解决方案。

Simple类,包含从列表中返回具有起始索引的10个元素的函数。

 import java.util.ArrayList; import java.util.List; public class TestTenElement { public static void main(String[] args) { // Getting all the element list from DB -- Here Creating Sample List List myList = new ArrayList(); // Dummy element list for (long i = 0; i < 51; i++) { myList.add(i); } // Calling function may be from different class System.out.println(getFiveElement(myList, 0)); // First Ten Element from StartIndex 0 System.out.println(getFiveElement(myList, 10)); // Second Ten Element from StartIndex 5 // ....... System.out.println(getFiveElement(myList, 50)); // If Last Iteration Gives remaining elements } // print ten element from list from the start index specified public static List getFiveElement(List myList, int startIndex) { List sub = new ArrayList(); sub = myList.subList(startIndex, Math.min(myList.size(), startIndex + 10)); return sub; } }