public static List<List<T>> divideList(List<T> originalList,int numParts) { if (numParts <= 0) { throw new IllegalArgumentException("The number of parts must be greater than zero."); } int totalSize = originalList.size(); int sizePerPart = totalSize / numParts; int remainder = totalSize % numParts; List<List<T>> result = new ArrayList<>(); int startIndex = 0; for (int i = 0; i < numParts; i++) { int currentPartSize = sizePerPart + (remainder > 0 ? 1 : 0); remainder--; int endIndex = startIndex + currentPartSize; result.add(new ArrayList<>(originalList.subList(startIndex, Math.min(endIndex, totalSize)))); startIndex = endIndex; if (startIndex >= totalSize) { // If all elements have been distributed, remaining parts will be empty lists for (int j = i + 1; j < numParts; j++) { result.add(new ArrayList<>()); } break; } } return result; }
java将一个list动态分成n个
最新推荐文章于 2024-06-12 11:11:42 发布