An overview,
During development, there was a requirement to split a List into sublists of a specified size. The requirement was very simple. Here are two ways to do this:
- Write your own Java code implementation
- Use the utility classes provided by Guava
Two, write Java code implementation
The implementation code is as follows:
public static <T> List<List<T>> partition(List<T> list, int size) {
List<List<T>> result = new ArrayList<>();
if (list == null) {
throw new NullPointerException("List cannot be null");
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be greater than 0");
}
if (list.size() < size) {
result.add(list);
} else {
int r = list.size() / size;
for (int i = 0; i < r; i++) {
List<T> subList = list.subList(i * size, (i + 1) * size);
result.add(subList);
}
if(r * size < list.size()) { List<T> subList = list.subList(r * size, list.size()); result.add(subList); }}return result;
}
Copy the code
Third, use the tool class provided by Guava
Step 1: Add dependencies
<! -- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.0 the jre</version>
</dependency>
Copy the code
Step 2: Call Lists. Partition
public static void main(String[] args) {
List<String> idList = new ArrayList<>();
for (int i = 0; i < 25; i++) {
idList.add(UUID.randomUUID().toString());
}
List<List<String>> partition = Lists.partition(idList, 3);
for(List<String> strings : partition) { System.out.println(strings.size()); System.out.println(strings); }}Copy the code