fork download
  1. /* package whatever; // don't place package name! */
  2. import java.text.SimpleDateFormat;
  3. import java.text.ParseException;
  4.  
  5. import java.util.Calendar;
  6. import java.util.Date;
  7. import java.util.HashSet;
  8. import java.util.Set;
  9. import java.util.Map;
  10. import java.util.TreeMap;
  11.  
  12.  
  13. /* Name of the class has to be "Main" only if the class is public. */
  14. class Ideone
  15. {
  16. public static void main (String[] args) throws java.lang.Exception
  17. {
  18. Set<MyDate> allDates = getAllDates();
  19. Map<String, Set<MyDate>> map = new TreeMap<>();
  20. for (MyDate date : allDates) {
  21. String key = date.getWeekStamp();
  22. if (map.get(key) == null) {
  23. map.put(key, new HashSet<MyDate>());
  24. }
  25. map.get(key).add(date);
  26. }
  27. printDates(map);
  28. }
  29.  
  30. public static Set<MyDate> getAllDates() {
  31. String dateFormat = "MM/dd/yyyy";
  32. String[] inputDates = {
  33. "04/01/2015",
  34. "04/02/2015",
  35. "04/03/2015",
  36. "04/04/2015",
  37. "04/05/2015",
  38. "04/06/2015",
  39. "04/07/2015",
  40. "04/08/2015",
  41. "04/09/2015"};
  42.  
  43. Set<MyDate> dates = new HashSet<>(inputDates.length);
  44. for (String s : inputDates) {
  45. MyDate date = new MyDate(s, dateFormat);
  46. dates.add(date);
  47. }
  48. return dates;
  49. }
  50.  
  51. public static void printDates(Map<String, Set<MyDate>> map) {
  52. int week = 0;
  53. for (Set<MyDate> set : map.values()) {
  54. week++;
  55. System.out.println("Week : " + week);
  56. for (MyDate date : set) {
  57. System.out.println(date.getDate());
  58. }
  59. }
  60. }
  61.  
  62. private static class MyDate {
  63. final Calendar cal;
  64.  
  65. public MyDate (String strDate, String dateFormat) {
  66. cal = Calendar.getInstance();
  67. try {
  68. SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
  69. Date date = sdf.parse(strDate);
  70. cal.setTime(date);
  71. }
  72. catch (ParseException e) {
  73. throw new IllegalArgumentException("Invalid date " + strDate);
  74. }
  75. }
  76.  
  77. public String getWeekStamp() {
  78. return cal.get(Calendar.YEAR) + "-" + cal.get(Calendar.WEEK_OF_YEAR);
  79. }
  80.  
  81. public Date getDate() {
  82. return cal.getTime();
  83. }
  84. }
  85.  
  86. }
Success #stdin #stdout 0.16s 321152KB
stdin
Standard input is empty
stdout
Week : 1
Wed Apr 01 00:00:00 GMT 2015
Sat Apr 04 00:00:00 GMT 2015
Thu Apr 02 00:00:00 GMT 2015
Fri Apr 03 00:00:00 GMT 2015
Week : 2
Sun Apr 05 00:00:00 GMT 2015
Tue Apr 07 00:00:00 GMT 2015
Thu Apr 09 00:00:00 GMT 2015
Mon Apr 06 00:00:00 GMT 2015
Wed Apr 08 00:00:00 GMT 2015