티스토리 뷰

Java List Partition

  • 어떤한 List에 대해서 일정한 비율로 세부 List로 나눠야 하는 경우가 있습니다.
  • 이때 간단하게 분할을 하는 방법에 대해서 알아보겠습니다. 

문제가정

  • 상황을 가정해보자면 한 List에 Integer값이 아래와 같이 10개가 들어있습니다. 
List<Integer> testList = new ArrayList<Integer>() {{
    add(0); add(1); add(2); add(3); add(4); add(5); add(6); add(7); add(8); add(9);
}};
  • 이 상황에서 List의 값을 3개씩 잘라서 하위 리스트로 분할 하고자 합니다.

해결방법

구현 형태는 여러가지가 될 수 있습니다.

Guava

  • Guava 라이브러리를 사용하면 List를 지정한 크기로 Sub List로 분할할 수 있습니다.
List<List<Integer>> listByGuava = Lists.partition(testList, testList.size() / 3);

//will be..
listByGuava = {Lists$RandomAccessPartition@1053}  size = 4
 0 = {ArrayList$SubList@1064}  size = 3
 1 = {ArrayList$SubList@1065}  size = 3
 2 = {ArrayList$SubList@1066}  size = 3
 3 = {ArrayList$SubList@1067}  size = 1

 

Apache Commons

  • Apache Coomons 라이브러리 역시 Guava와 비슷한 형태의 메서드를 지원합니다. 
List<List<Integer>> listByApache = ListUtils.partition(testList, testList.size() / 3);

//will be..
listByApache = {ListUtils$Partition@1056}  size = 4
 0 = {ArrayList$SubList@1083}  size = 3
 1 = {ArrayList$SubList@1084}  size = 3
 2 = {ArrayList$SubList@1085}  size = 3
 3 = {ArrayList$SubList@1086}  size = 1

 

Java8 Collectors groupingBy

  • Java8 Collectors.groupingBy() 메서드를 이용하면 아래와 같은 형태로 구현할 수 있습니다.
    • groupingBy() 의 출력은 Map이기 때문에 List로 옮겨주어야 함 
Map<Integer, List<Integer>> groups = testList.stream().collect(Collectors.groupingBy(i -> i / 3));
List<List<Integer>> listByCollectors = new ArrayList<>(groups.values());

//will be..
listByCollectors = {ArrayList@1058}  size = 4
 0 = {ArrayList@1093}  size = 3
 1 = {ArrayList@1094}  size = 3
 2 = {ArrayList@1095}  size = 3
 3 = {ArrayList@1096}  size = 1

참고

 

Partition a List in Java | Baeldung

How to Partition a List using Guava or Apache Commons Collections.

www.baeldung.com

 

반응형
댓글