English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Pagination Example Code for ArrayList

java pagination for ArrayList

Overview

Interactions between systems are usually in the form of interfaces. Suppose System B provides a batch query interface, which limits the query to50 data, while we actually need to query500 data, at this time, you can take this500 data for batch operations, split10This call to the batch interface of System B.

If the query interface of System B uses List as input parameter, then to implement batch calls, you can use the subList method of ArrayList to handle it.

Code

Definition of sublist method:

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

It is only necessary to accurately calculate fromIndex and toIndex.

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});
  }
}

Page Sorting 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});
    //Total number of records
    Integer totalCount = datas.size();
    //How many times to process
    Integer requestCount = totalCount / PAGE_SIZE;
    for (int i = 0; i <= requestCount; i++) {
      Integer fromIndex = i * PAGE_SIZE;
      //If the total number is less than PAGE_SIZE, toIndex uses totalCount directly to prevent array out of bounds
      int toIndex = Math.min(totalCount, (i + 1) * PAGE_SIZE);
      List<Long> subList = datas.subList(fromIndex, toIndex);
      System.out.println(subList);
      //When the total number is less than one page or exactly one page, you can exit the for loop after processing once.
      if (toIndex == totalCount) {
        break;
      }
    }
  }
}

Test scenarios

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

The above three cases can pass normally.

Thank you for reading, I hope it can help everyone, thank you for your support to our website!

You May Also Like