java pages ArrayList instance code

  • 2020-06-07 04:36:28
  • OfStack

java pages ArrayList

An overview of the

The interaction between systems, usually in the form of interfaces. Suppose that B system provides a batch query interface, which can only query 50 pieces of data at a time, but we actually need to query 500 pieces of data. At this time, we can do batch operation on these 500 pieces of data and call the batch interface of B system in 10 times.

If the query interface of the B system USES List as a reference, the subList method of ArrayList can be used to implement batch calls.

code

Definition of sublist method:


  List<E> subList(int fromIndex, int toIndex);

Just calculate fromIndex and toIndex exactly.

Data preparation


public class TestArrayList {

  public static void main(String[] args) {
    List<Long> datas = Arrays.asList(new Long [] {1L,2L,3L,4L,5L,6L,7L});
  }
}

Paging algorithm


import java.util.Arrays;
import java.util.List;

public class TestArrayList {

  private static final Integer PAGE_SIZE = 3;
  public static void main(String[] args) {
    List<Long> datas = Arrays.asList(new Long [] {1L,2L,3L,4L,5L,6L,7L,8L});

    // The total number of records 
    Integer totalCount = datas.size();

    // How many times to deal with 
    Integer requestCount = totalCount / PAGE_SIZE;

    for (int i = 0; i <= requestCount; i++) {
      Integer fromIndex = i * PAGE_SIZE;
      // If the total is less than PAGE_SIZE, To prevent the array from crossing boundaries ,toIndex Direct use of totalCount Can be 
      int toIndex = Math.min(totalCount, (i + 1) * PAGE_SIZE);
      List<Long> subList = datas.subList(fromIndex, toIndex);
      System.out.println(subList);
      // The total number of less than 1 Pages or exactly equal to 1 The page , You just need to deal with 1 Then you can quit for The loop 
      if (toIndex == totalCount) {
        break;
      }
    }

  }
}

Test scenarios

1. The total number is less than 1 page
2. The total is exactly one page
3. The total amount is more than 1 page

All the above three case can pass normally.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: