[JAVA] ArrayList를 n개씩 분할하는 코드

moonno·2024년 4월 12일

JAVA

목록 보기
1/1
post-thumbnail

코드 형식

import java.util.ArrayList;
import java.util.List;

public class ListDivider {
    public static void main(String[] args) {
    
        // 0부터 99까지의 숫자를 갖는 리스트 생성
        List<Integer> numberList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            numberList.add(i);
        }

        // 리스트를 10개씩 분할하여 출력
        int size = numberList.size();
        for (int i = 0; i < size; i += 10) {
            List<Integer> subList = numberList.subList(i, Math.min(i + 10, size));
            System.out.println(subList);
        }
    }
}

실제 사용 예제 코드


public class TestClass {
    private final SelectMapper selectMapper;
    private final InsertMapper insertMapper;
    
    public static void main(String[] args) {
        ReqDTO reqDTO = new ReqDTO();

        // 리스트 조회
        List<RespDTO> resultList = selectMapper.getList(reqDTO);

        // 조회된 리스트를 분할하여 저장
        if (!resultList.isEmpty()) {
            int listSize = resultList.size();
            int limitSize = 1000;
            for (int idx = 0; idx < listSize; idx += limitSize) {
                reqDTO.setRsultList(resultList.subList(idx, Math.min(idx + limitSize, listSize)));
                insertMapper.insertList(reqDTO);
            }
        }    
    
    }
}

참고 : MyBatis에서 List 한번에 저장하는 코드


profile
Developer Moona

0개의 댓글