I am trying to sort items by category. My thought was to use the category of the first item in the item list, iterate down the list and move any items in the same category to a new list, appending a category name after completing all items. Then start the loop again, on the original list (with the removed items), repeat until the original list has nothing in it (i.e. everything was moved in to a sortedList by category).
My code was set up like this:
List<Food> foodList; //some arraylist of foods, we want to sort by category (fruit, veg, meat).
List<Food> sortedList; //arraylist sorted by category.
while ( !foodList.isEmpty ) {
String category = foodList.get(0).getCategory;
for ( Food f : foodList ) {
if ( f.category.equals(category) ) {
sortedList.add(f);
foodList.remove(f);
}
}
sortedList.add(category) //like a category heading.
}
//flip sortedList to have categories on top...
Is there a different/better way of doing this? My current working method seems really crappy. It is basically figuring out every category in the list, compare every item in the list by every category, iterating through the categories and just adding to a sorted list. There must be a more performant way to do this, which my above solution should help, if I can get it to work. Any help would be appreciated.