如何使用<Integer> Java 将列表转换为列表<列表<Integer>>?修复内部列表的大小



我有一个要批量处理的数字列表。

example 1:
input1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] //(List of number)
input2 = 5 //(Batch size)
output = [[1, 2, 3, 4, 5], [6, 7, 8, 9]]
example 2:
input1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]//(List of number) 
input2 = 5//(Batch size)
output = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

下面是一个使用java流的例子,

public static void main(String[] args) throws Exception {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
int batchSize = 5;
AtomicInteger ai = new AtomicInteger();
Collection<List<Integer>> chunkedOrders = list.stream()
.collect(Collectors.groupingBy(item -> ai.getAndIncrement() / batchSize)).values();
System.out.println("Your innerlist = " + chunkedOrders);
chunkedOrders.forEach(chunk -> {
System.out.println("Processing" + " " + chunk.size() + " " + " data, sublist = " + chunk);
});
}

输出:

Your innerlist = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11]]
Processing 5  data, sublist = [1, 2, 3, 4, 5]
Processing 5  data, sublist = [6, 7, 8, 9, 10]
Processing 1  data, sublist = [11]
public class Solution {
public static <T> List<List<T>> breaks(List<T> tList, int length) {
if (length <= 0)
throw new IllegalArgumentException(
"The chosen length is less than or equal to zero: " + length
);
int size = tList.size();
if (size <= 0)
return new ArrayList<>();
int fullChunks = (size - 1) / length;
return IntStream.range(0, fullChunks + 1).mapToObj(
n -> tList.subList(n * length, n == fullChunks ? size : (n + 1) * length)
).collect(Collectors.toList());
}
public static void main(String args[]) {
// Original list
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
// Printing of the original list
System.out.println(list1);
// Broken list
List<List<Integer>> list2 = breaks(list1,5);
// Print of the broken list
System.out.println(list2);
}
}

相关内容

最新更新