我需要一些示例代碼或算法來調整List<List<Integer>>
應在下一工作方式的數量:爪哇 - 調整嵌套列表
讓我們想象一下,我們有下一個newSize
和incomingList
(僞):
int newSize = 4;
List<List<Integer>> incomingList = List(List(1,2,3),List(4,5,6),List(7,8,9);
List<List<Integer>> result = resizeListOfNestedList(newSize, incomingList)
newSize
整數集的incomingList
和resizeListOfNestedList
新大小應返回下一個結果爲非奇數(例如,4):
List(List(1,2),List(3,4),List(5,6),List(7,8)
和下如果新尺寸是奇數(例如3):
List(List(1,2),List(3,4,5),List(6,7,8)
newSize
總是大於incomingList.size()
我希望任何建議。
更新
隨着google.common.Lists
幫助下,我已經完成守則草案(是的,聞起來),我希望它會幫助別人。
在我的案例方法接收不同incomingList.size()
S和newSize
PARAMS和很明顯,incomingList.size()/newSize
將返回雙精度值(例如,進入則爲list.size()= 1000,但我們需要「壓縮」它600元),所以我無法始終使用Lists.partition
。 expandList
是更好的下一個代碼後致電:
int maxSplitValue = (int) Math.ceil((double) incomingList.size()/newSize);
List<List<Integer>> firstPortionValues = Lists.partition(
incomingList, maxSplitValue
);//size can be less than required after double to int upper round
if (firstPortionValues.size() < maxSplitValue) {
List<List<Integer>> expandedList = expandList(firstPortionValues, maxSplitValue)
}
結果:
Incoming list:[[0, 1], [2, 3]]
New size value: 3
Outcoming list:[[0], [1], [2, 3]]
Incoming list:[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]
New size value: 4
Outcoming list:[[0.0], [1.0], [2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]
代碼:
public List<List<Integer>> expandList(List<List<Integer>> incomingList, int newSize) {
List<List<Integer>> resultList = new ArrayList<>();
for (int index = 0; index < incomingList.size(); index++) {
List<Integer> nodeList = incomingList.get(index);
final int minPortionValue = getMinPortionValue(
incomingList.size(), resultList.size(), nodeList.size(), index, newSize
);
List<List<Integer>> portionResult = splitNodeList(new ArrayList<>(nodeList), minPortionValue);
resultList.addAll(portionResult);
}
return resultList;
}
private int getMinPortionValue(int listSize, int resultListSize, int listElementSize, int index, int newSize) {
if (listElementSize > 1) {
int maxPortionValue = listElementSize % 2 == 0 ? listElementSize/2 : --listElementSize;
boolean isOkUseMaxPortionValue = maxPortionValue + listSize - index + resultListSize <= newSize;
if (isOkUseMaxPortionValue) {
return maxPortionValue;
} else {
return getMinPortionValue(listSize, resultListSize, listElementSize - 1, index, newSize);
}
} else {
return 0;
}
}
private List<List<Integer>> splitNodeList(List<Integer> nodeList, int minSplitValue) {
List<List<Integer>> result = new ArrayList<>();
if (minSplitValue > 0) {
result.addAll(Lists.partition(nodeList, minSplitValue));
return result;
} else {
result.add(nodeList);
return result;
}
}
請告訴我們您到目前爲止所嘗試過的。 – eltabo
@eltabo如果我有一些有用的代碼草稿,我會用問題發佈它。請注意,我沒有要求完整的解決方案。另外,我想應該有一些java庫可以幫助。 – unpc
任務不夠清楚,您是不是在示例中丟失了9的值? –