0

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Anil Shrestha
  • 1,180
  • 11
  • 16
  • see this example https://stackoverflow.com/a/36678648/3883957 which uses `Collectors.groupingBy` – yishaiz Sep 14 '17 at 07:31
  • i looked the example but it says lamda expression is not supported at this level – Anil Shrestha Sep 14 '17 at 07:41
  • maybe this answer https://stackoverflow.com/a/35524722/3883957 which uses Apache Commons Collections will help? – yishaiz Sep 14 '17 at 08:44
  • What exactly is `CalendarDay{2017-8-13}` as a data type? Is it a string, a custom class or what? Because I have an idea but I need some more details to see if it works. – Iulian Popescu Sep 14 '17 at 10:26
  • it is in calendarday format but it can be string also if you have idea with string than it is string – Anil Shrestha Sep 14 '17 at 10:28

2 Answers2

1

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}]
}
Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
0

You can get the value of the month in each element and then put it into a different array depending on the value

U2647
  • 450
  • 4
  • 10