Questions
I am having the list . List has 28 records. I need to split the records in the list into 13 + 13 + 2 in the code. Is it possible?
Solution
public with sharing class Lists {
public static List<List<Object>> doPartions(List<Object> records, Integer size, Type destType){
checkNotNull(records);
checkArgument(size > 0);
checkNotNull(destType);
return new Partition(records, size, destType).doPartition();
}
private static void checkNotNull(Object reference) {
if (reference == null) {
throw new NullPointerException();
}
}
private static void checkArgument(Boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
private class Partition{
private List<Object> items;
private Integer splitSize;
private Type destType;
Partition(List<Object> records, Integer size, Type destType){
this.items = records;
this.splitSize = size;
this.destType = destType;
}
List<List<Object>> doPartition(){
List<List<Object>> result = (List<List<Object>>)destType.newInstance();
List<Object> protoList = items.clone();
protoList.clear();
List<Object> tempList = protoList.clone();
Integer index = 0, count = 0, size = items.size();
while(index < size) {
tempList.add(items.get(index++));
++count;
if(count == splitSize) {
result.add(tempList);
tempList = protoList.clone();
count = 0;
}
}
if(!tempList.isEmpty()) {
result.add(tempList);
}
return result;
}
}
public class IllegalArgumentException extends Exception {}
}
Usage
List<Integer> input = new List<Integer> {1, 2, 3, 4, 5, 6, 7};
List<List<Integer>> result = (List<List<Integer>>) Lists.doPartions(input, 2, List<List<Integer>>.class);
System.debug(result);
DEBUG|((1, 2), (3, 4), (5, 6), (7))
轻量化
public with sharing class Utility {
/**
* Desc: split one list into multiple list
* Usage: List<List<Integer>> result = (List<List<Integer>>) Utility.doListPartition(new List<Integer> {1, 2, 3}, 2, List<List<Integer>>.class);
*/
public static List<List<Object>> doListPartition(List<Object> items, Integer splitSize, Type destType) {
if(items == null || destType == null) throw new NullPointerException();
if (splitSize <= 0) throw new IllegalArgumentException();
List<List<Object>> result = (List<List<Object>>)destType.newInstance();
List<Object> protoList = items.clone();
protoList.clear();
List<Object> tempList = protoList.clone();
Integer index = 0, count = 0, size = items.size();
while(index < size) {
tempList.add(items.get(index++));
++count;
if(count == splitSize) {
result.add(tempList);
tempList = protoList.clone();
count = 0;
}
}
if(!tempList.isEmpty()) result.add(tempList);
return result;
}
public class IllegalArgumentException extends Exception {}
}