Home > Java > javaTutorial > Introduction to methods of List segmentation operation in Java

Introduction to methods of List segmentation operation in Java

黄舟
Release: 2017-09-26 10:00:04
Original
2032 people have browsed it

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());
    }
  }
}
Copy after login

Test:

1, flag = 1


##

第1组:[aaa]
第2组:[bbb]
第3组:[ccc]
第4组:[ddd]
第5组:[eee]
第6组:[fff]
第7组:[ggg]
Copy after login

2, flag = 2

##

第1组:[aaa, bbb]
第2组:[ccc, ddd]
第3组:[eee, fff]
第4组:[ggg]
Copy after login

3, flag = 10

第1组:[aaa, bbb, ccc, ddd, eee, fff, ggg]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template