I want to get all the objects from the list and put them into a Map grouped by creation date, which means the map is like this: Map<String, List<MyObject>>. The MyObject object has a field that stores its creation date.
I’ve thought of doing a nested while loop that looks like this:
public Map<String, List<Expense>> getExpensesSorted(SortType type){
Map<String, List<Expense>> map = new HashMap<String, List<Expense>>();
List<Expense> expenses = getAllExpenses(budgetId).getExpenses()
.getList();
if (type.equals(SortType.DAY)) {
Iterator<Expense> expIter = expenses.iterator();
while (expIter.hasNext()) {
List<Expense> list = new ArrayList<Expense>();
Expense exp = (Expense) expIter.next();
list.add(exp);
String day = exp.getDate().format("YYYY-MM-DD");
expIter.remove();
while (expIter.hasNext()) {
Expense exp2 = (Expense) expIter.next();
if (exp2.getDate().format("YYYY-MM-DD").equals(day)) {
list.add(exp2);
expIter.remove();
}
}
map.put(day, expenses);
}
} else if (type.equals(SortType.WEEK)) {
...
} else if (type.equals(SortType.TYPE)) {
...
} else if (type.equals(SortType.CATEGORY)) {
...
}
return map;
}
But this is wrong, it only gets all the ones that have the same day as the first element, so my map ends up having only one element.
I seriously don’t know how to solve this…
Thanks in advance for any help.
Something like this should do the job. I didn’t compile it though.