This article mainly introduces relevant information about examples of List segmentation operations in Java. I hope that through this article, everyone can master the method of implementing list segmentation. Friends who need it can refer to it
Examples of List segmentation operations in java
Question: Suppose system A queries a very large List, and now system B wants to get this list to export reports, but system B’s deployment environment Conditions are limited and the memory cannot accommodate such a large List. At this time, we need to split the List and export it one by one.
If we follow the traditional method, it may be more cumbersome. We can use the subList method in List to achieve it. The code is as follows:
import java.util.ArrayList; import java.util.List; public class listTest { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("aaa");//index_0 list.add("bbb");//index_1 list.add("ccc");//index_2 list.add("ddd");//index_3 list.add("eee");//index_4 list.add("fff");//index_5 list.add("ggg");//index_6 int flag = 3;//每次取的数据 int size = list.size(); int temp = size / flag + 1; boolean special = size % flag == 0; List<String> cutList = null; for (int i = 0; i < temp; i++) { if (i == temp - 1) { if (special) { break; } cutList = list.subList(flag * i, size); } else { cutList = list.subList(flag * i, flag * (i + 1)); } System.out.println("第" + (i + 1) + "组:" + cutList.toString()); } } }
Test:
1, flag = 1
##
第1组:[aaa] 第2组:[bbb] 第3组:[ccc] 第4组:[ddd] 第5组:[eee] 第6组:[fff] 第7组:[ggg]2, flag = 2
##
第1组:[aaa, bbb] 第2组:[ccc, ddd] 第3组:[eee, fff] 第4组:[ggg]
第1组:[aaa, bbb, ccc, ddd, eee, fff, ggg]
The above is the detailed content of Introduction to methods of List segmentation operation in Java. For more information, please follow other related articles on the PHP Chinese website!