2017-05-23 88 views
3

我有一個非額定項目的列表,我希望它們被分割成5倍。目前,我已經完成了,我只是試圖平均分成塊,最後一塊是所謂的「擴展」塊,這對我造成了問題。將分割列表分成「最大」相等大小的塊

當我有nonRatedItems = {1,2,3,4,5,6,7,8},那麼塊是:

1 
2 
3 
4 
5 6 7 8 

我想避免這種情況,使輸出爲:

1 6 
2 7 
3 8 
4 
5 

電流源:

Collections.shuffle(nonRatedItems); 
    nonRatedItems = nonRatedItems.subList(0, (int) Math.ceil(nonRatedItems.size() * 0.2)); 
    int tfoldSize = nonRatedItems.size()/5; 
    List<List<Integer>> negativeTestFolds = new ArrayList<List<Integer>>(); 
    if (tfoldSize < 1) { 
     nonRatedItems.stream().map(Lists::newArrayList).collect(Collectors.toCollection(() -> negativeTestFolds)); 
       } else { 
        for (int i = 0; i < 5; i++) { 
         int endIndex = i < 4 ? (i + 1) * tfoldSize : nonRatedItems.size(); 
         negativeTestFolds.add(nonRatedItems.subList(i * tfoldSize, endIndex)); 
        } 
       } 

任何建議/幫助表示讚賞

回答

2

它總是5倍嗎? 爲什麼不循環列表?像

List<Integer>[] folds = new List<Integer>[5]; 
for(int i = 0; i < 5; i++) 
{ 
    folds[i] = new LinkedList<Integer>(); 
} 

for (int i = 0; i < nonRatedItems.size(); i++) 
{ 
    folds[i % 5].add(nonRatedItems.get(i)); 
} 
+0

其實,它會'k' =摺疊。所以,會給出'k'。但是,如果'i = 6',怎麼可能做'摺疊[6] .add(nonRatedItems.get(6));' – Cap

+0

@CollinD當然,我錯過了它 –

+0

'摺疊[i% 5]。新增(nonRatedItems.get(I));' – Cap

相關問題