Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : How do I group all java Dates in their corresponding week?

Tags:

java

date

Problem:

I have a large list of dates and I need to arrange them all by week.

Question: How do I group dates by the week of the year that they are in?

Example Data Set

Date date = new SimpleDateFormat.parse("04/01/2015")
Date date = new SimpleDateFormat.parse("04/02/2015")
Date date = new SimpleDateFormat.parse("04/03/2015")
Date date = new SimpleDateFormat.parse("04/04/2015")
Date date = new SimpleDateFormat.parse("04/05/2015")
Date date = new SimpleDateFormat.parse("04/06/2015")
Date date = new SimpleDateFormat.parse("04/07/2015")
Date date = new SimpleDateFormat.parse("04/08/2015")
Date date = new SimpleDateFormat.parse("04/09/2015")

Desired Output

HashMap<Date, Date> hashMap = groupByWeek(ArrayList<Date> dates);

printWeeklyGroupedDates();

Week 1:
04/01/2015
04/02/2015
04/03/2015
04/04/2015
04/05/2015
04/06/2015
04/07/2015
Week 2:
04/08/2015
04/09/2015

What I've Tried

public Date getWhichYearlyWeek(Date date){

  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  cal.get(Calendear.WEEK_OF_YEAR);

  //Need to return this as 'Date' but indicate which week this is for the TreeMap functionality below          

  return cal.getTime();
}


public TreeMap<Date, ArrayList<Date>> getWeeklyMappedDates(ArrayList<Date> dateArray){

  TreeMap<Date, ArrayList<Date>> treeMap = new TreeMap<Date, ArrayList<Date>>

  for(Date i : dateArray){

    Date date = getWhichYearlyWeek(date);

    if(!treeMap.containsKey(date))
      treeMap.get(date).add(date);
    else
      treeMap.put(date, new ArrayList<Date>());
  }

  return treeMap;
}
like image 435
stackoverflow Avatar asked Apr 29 '15 20:04

stackoverflow


1 Answers

If Java 8 were available:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
TemporalField weekOfYear = WeekFields.of(Locale.getDefault()).weekOfYear();

Stream.of(
      "04/01/2015"
    , "04/02/2015"
    , "04/03/2015"
    , "04/04/2015"
    , "04/05/2015"
    , "04/06/2015"
    , "04/07/2015"
    , "04/08/2015"
    , "04/09/2015"
)
.collect(Collectors.groupingBy(
    d -> LocalDate.parse(d, formatter).get(weekOfYear),
    LinkedHashMap::new,
    Collectors.toList()
))
.forEach((week, dates) -> {
    System.out.println("Week " + week + ":");

    dates.forEach(System.out::println);
});

This prints (using de_CH locale on my computer)

Week 14:
04/01/2015
04/02/2015
04/03/2015
04/04/2015
04/05/2015
Week 15:
04/06/2015
04/07/2015
04/08/2015
04/09/2015
like image 164
Lukas Eder Avatar answered Oct 31 '22 17:10

Lukas Eder