1

I am trying to implement this method:

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

The method takes an ArrayList of Strings and a number that represents the number of words in each group as parameters and then returns an ArrayList made of ArrayLists that contain groups of words according to the groupNumber parameter. For example, there is an ArrayList of 20 strings and I want to group that ArrayList into groups of 5 so I call the method like this:

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

I am pretty sure that I need to have a for loop with another for loop nested inside, but I am not sure how to implement it.

How do I implement this method?

3 Answers 3

3

With Guava:

List<List<String>> groupedWords = Lists.partition(words, 5); 
Sign up to request clarification or add additional context in comments.

Comments

2

Something like this should work:

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)); } 

I haven't tested this code but basically I'm using the fact that integer division is always rounding to the next lowest Integer. Example: 4/5=0.8 and is rounded to 0.

2 Comments

It's throwing an IndexOutOfBoundsException for grouped at the grouped.get(i).add(words.get(i)) line
I have edited the answer it should work now...I think.
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; } 

This is simple Java Collections Soultion.

Suggestion : As a return type you should use ArrayList<ArrayList<String>>, and this should be the type for result also.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.