Joda time
For Android, you should use the Joda-Time library, not the old java.util.Date/.Calendar classes, which have proven to be so troublesome. Please note that some alternative releases of Joda-Time have been released to work around the Android issue with initial slowness.
Joda-Time includes the YearMonth class, just what we need to represent the year and month as the key to keeping track of date values, Joda-Time also has a LocalDate class to represent the value only for a date without any time or time zone.
We define a formatter with the template "MMMM dd yyyy" for parsing strings. Please note that we specify Locale with English as the formatting language so that this code works successfully on the JVM, where the current language defaults to a language other than English. What language is used in the analysis of the names of the months "January", "February", etc.
We collect LocalDate values as a SortedSet , which serves two purposes: (a) eliminates duplicates and (b) keeps dates sorted. Our implementation of SortedSet is a TreeSet . Each specified object is assigned a YearMonth object. A TreeMap keeps track of which YearMonth has a set of dates. We use TreeMap , not HashMap , to store the keys in sorted order since it implements SortedMap . If you had a huge number of elements and sorting by key was not critical, then HashMap could be the best choice for performance.
String[] input = { "January 20 2015" , "February 12 2015" , "February 20 2015" , "June 21 2015" , "July 12 2015" , "July 28 2015" , "July 30 2015" , "September 24 2015" , "December 31 2015" }; Map<YearMonth , SortedSet<LocalDate>> map = new TreeMap<>(); DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMMM dd yyyy" ).withLocale( Locale.ENGLISH ); for ( String string : input ) { LocalDate localDate = formatter.parseLocalDate( string ); YearMonth yearMonth = new YearMonth( localDate ); if ( ! map.containsKey( yearMonth ) ) {
Dump for the console.
System.out.println( "input: " + Arrays.toString( input ) ); System.out.println( "map: " + map );
At startup.
input: [January 20, 2015, February 12, 2015, February 20, 2015, June 21, 2015, July 12, 2015, July 28, 2015, July 30, 2015, September 24, 2015, December 31, 2015]
map: {2015-01 = [2015-01-20], 2015-02 = [2015-02-12, 2015-02-20], 2015-06 = [2015-06-21], 2015-07 = [ 2015-07-12, 2015-07-28, 2015-07-30], 2015-09 = [2015-09-24], 2015-12 = [2015-12-31]}
java.time
In Java 8 and later, you can use the new built-in java.time framework. Joda-Time has been an inspiration for this structure. The code will be very similar in case of this answer.