κ°œλ°œμƒν™œ/Java

[Java] List λ‚˜λˆ„κΈ°

cocococo331 2022. 5. 23. 21:03

As-Is νž˜λ“€κ²Œ λ‚˜λˆ„λŠ” 법 (subList)

  public static void main(String[] args) {
    List<Integer> integerList = new ArrayList<>();

    for(int i = 0; i<10000; i++) {
        integerList.add(i);
    }
    int size = integerList.size();   
    
    int page = size / 100 + 1;
    for (int i = 0; i < page; i++) {
        int startIndex = i * 100;
        int endIndex = i == page - 1 ? size  : (i + 1) * 100;
        List<Integer> subList = integerList.subList(startIndex, endIndex);
    }

}
  • List<E> subList(int fromIndex, int toIndex); μ‚¬μš©
  • λ©”λͺ¨λ¦¬ μ΄μŠˆλ‚˜, λΆ€λͺ¨Listκ°€ λ°”λ€œμ— 따라 SubListκ°€ 영ν–₯을 λ°›μ•„ Exception을 뱉을 수 있기 λ•Œλ¬Έμ— newArrayList<>(integerList.subList(startIndex, endIndex)); // μƒˆλ‘œ μƒμ„±ν•˜λŠ” 것을 ꢌμž₯

 

To-Be κ°„λ‹¨ν•˜κ²Œ λ‚˜λˆ„λŠ” 법 : Guava Library μ‚¬μš© (Lists.partition)

public static void main(String[] args) {
    List<Integer> integerList = new ArrayList<>();

    for(int i = 0; i<10000; i++) {
        integerList.add(i);
    }

    List<List<Integer>> lists = Lists.partition(integerList, 100);
}