티스토리 뷰
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
반응형
'프로그래밍 > JAVA' 카테고리의 다른 글
[Java] 함수형 인터페이스 예외 처리 방법 (0) | 2020.07.29 |
---|---|
[Java] 함수형 인터페이스 소개 및 사용 (0) | 2020.07.28 |
(Java) Gmail SMTP 구현시 "AuthenticationFailedException: 535-5.7.8 Username and Password not accepted" 에러 해결법 (0) | 2020.05.26 |
(Java) 장비, 시스템 메모리(RAM) 값 알아내는 방법 (feat. OSHI 라이브러리 사용법) (0) | 2020.05.07 |
(Java) 파일 FTP 프로토콜 전송 기능 구현방법 (FTP Client 구현) (0) | 2020.05.05 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- JavaFX Window Close
- 방통대 과제물
- 이펙티브자바
- Java UI
- 텐트
- 스프링부트
- windows
- 자전거
- git
- effective java
- 이펙티브
- springboot
- 일본여행
- 이펙티브 자바
- JavaFX 테이블뷰
- JavaFX Table View
- intelij
- JavaFX 종료
- TableView
- 자바
- 배낭여행
- 일본 여행
- effectivejava
- 배낭 여행
- 일본 배낭여행
- java
- 자전거 여행
- 일본 자전거 여행
- JavaFX
- 인텔리제이
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함