If I need to iterate over a list and try to group elements together, what is the best way to go about this?
Let's say for example we have the following objects to loop through:
People
|---Jimmy
| -Country: Canada
|---Johnny
| -Country: Ireland
|---Vinny
| -Country: Italy
|---Tommy
| -Country: Ireland
|---Wendy
| -Country: Canada
I need to go through each person, and create a group with people in the same country.
For example, it starts with Jimmy, iterates through the list to find anyone in Canada, only Wendy matches the same country so they both get grouped together. When iterating to the next person, we don't want to go through the same process for Wendy (as she is already grouped). So we need to remove her from the original list.
I've read that the iterator is best for removing elements from an active iterating list. However that only removes the current element. Is there any other suggestions? I was thinking a while loop and then a for loop which iterates to match.
For example:
while (!originalPersonList.isEmpty()) {
ArrayList<Person> newGroup = new ArrayList<Integer>();
List<Integer> indexToRemove = new ArrayList<Integer>();
newGroup.add(0);
indexToRemove.add(0);
for (int i=1; i < originalPersonList.size(); i++) {
if (originalPersonList.get(0).getCountry() == originalPersonList.get(i).getCountry()) {
indexToRemove.add(i);
newGroup.add(i);
}
}
originalPersonList.removeAll(indexToRemove);
}
This was the direction I was going towards, but I feel there is a more elegant solution out there.
Apologies - I feel I should have highlighted this at the start. I'm restricted to Java 7.