Issue
I have an array that contains calendardays like this. this array may contain data from all the months.
calendarday: [CalendarDay{2017-8-13}, CalendarDay{2017-8-14}, CalendarDay{2017-9-18}, CalendarDay{2017-9-19}, CalendarDay{2017-10-15}, CalendarDay{2017-10-16}]
I want to split those array values by its months into different arrays or same arrays with different keys. like this
calendarday: [CalendarDay{2017-8-13}, CalendarDay{2017-8-14}]
calendardayone: [CalendarDay{2017-9-18}, CalendarDay{2017-9-19}]
or like this
calendarday: [
0:[CalendarDay{2017-8-13}, CalendarDay{2017-8-14}],
1:[CalendarDay{2017-9-18}, CalendarDay{2017-9-19}],
2:[CalendarDay{2017-10-15}, CalendarDay{2017-10-16}]
]
One way I found is to check if condition for all the month and split those array. But I don't want to do that. Is there any alternative methods so that I will not have to check if condition for all months?
Solution
This is the solution I was thinking about: keep all the CalendarDay
in a dictionary with the key being the month. So we start with something like this:
String[] array = {"CalendarDay{2017-8-13}", "CalendarDay{2017-8-14}", "CalendarDay{2017-9-18}", "CalendarDay{2017-9-19}", "CalendarDay{2017-10-15}", "CalendarDay{2017-10-16}"};
Then simply iterate the array, split each string and save it to the dictionary:
Map<String, ArrayList<String>> dictionary = new HashMap<String, ArrayList<String>>();
for (String currentString : array) {
String month = currentString.split("-")[1];
ArrayList<String> values = dictionary.get(month);
if (values == null) {
values = new ArrayList<String>();
}
values.add(currentString);
dictionary.put(month, values);
}
And we end up with something like this:
{
8=[CalendarDay{2017-8-13}, CalendarDay{2017-8-14}],
9=[CalendarDay{2017-9-18}, CalendarDay{2017-9-19}],
10=[CalendarDay{2017-10-15}, CalendarDay{2017-10-16}]
}
Answered By - Iulian Popescu
Answer Checked By - Clifford M. (JavaFixing Volunteer)