2016-03-13 67 views
1

我試圖實現此方法:如何將ArrayList分解成組?

public ArrayList<ArrayList> groupWords(ArrayList<String> scrambledWords, int groupNumber); 

該方法以字符串的ArrayList和一個數字,表示字的每個組作爲參數的數量,然後返回由包含的基團的ArrayLists的ArrayList根據groupNumber參數輸入單詞。例如,有20串的一個ArrayList,我想組ArrayList的成5組,所以我稱這樣的方法:

ArrayList<ArrayList> groupedWords = groupWords(ArrayList, 5); 

我敢肯定,我需要有一個與另一個循環for循環嵌套在裏面,但我不知道如何實現它。

如何實現此方法?

回答

3

隨着Guava

List<List<String>> groupedWords = Lists.partition(words, 5); 
2

像這樣的東西應該工作:

ArrayList<ArrayList<String>> grouped = new ArrayList<>(); 
for(int i = 0; i < words.size(); i++) { 
    int index = i/groupSize; 
    if(grouped.size()-1 < index) 
     grouped.add(new ArrayList<>()); 
    grouped.get(index).add(words.get(i)); 
} 

我沒有測試代碼,但基本上我使用的事實,整數除法總是四捨五入到下一個最低的整數。 實施例:4/5 = 0.8,被舍入爲0

+0

它引發了一個IndexOutOfBoundsException分組在GROUPED.get(i).add(words.get(i))行 – cjones3724

+0

我編輯了答案它現在應該工作......我想。 – Garuno

+0

它現在謝謝! – cjones3724

0
public ArrayList<ArrayList> groupWords(ArrayList<String> scrambledWords, int groupNumber){ 
      int arraySize = scrambledWords.size(); 
      int count = 0; 
      ArrayList<ArrayList> result = new ArrayList<>(); 
      ArrayList<String> subResult = new ArrayList<>(); 
      for(int i = 0 ; i < arraySize; i++){ 
        if(count == groupNumber){ 
          count = 0; 
          result.add(subResult); 
          subResult = new ArrayList<>(); 
        } 
        subResult.add(scrambledWords.get(i)); 
        count++; 
      } 
      return result; 
} 

這是簡單的Java類別Soultion。

建議:作爲返回類型,您應該使用ArrayList<ArrayList<String>>,這也應該是結果的類型。