0

I have a List of Object made in this way:

public class Object{
    private Date date;
    private double value;

    //getters and setters
}

I need to take only Objects with hourly frequence.

My idea was to use a Java8 stream and groupingBy function in this way

Map<Integer, List<Object>> map = objects()
    .collect(Collectors.groupingBy(x -> x.getDate().get(ChronoField.HOUR_OF_DAY)));

but in this way i only take 24 elements (one per hour of day) even if I have multiple days in my list. How can i group by day/hour?

Fábio Nascimento
  • 2,644
  • 1
  • 21
  • 27
MarioC
  • 2,934
  • 15
  • 59
  • 111
  • Can you group by day and then for each day group by hour? – John Apr 23 '19 at 14:07
  • 1
    Possible duplicate of [Group by multiple field names in java 8](https://stackoverflow.com/questions/28342814/group-by-multiple-field-names-in-java-8) – takendarkk Apr 23 '19 at 14:08

2 Answers2

3

I strongly suggest you use a LocalDateTime here instead of Date.

Basically, you don't want to group by the hour number. You want to put each different hour in time in a different group, right? That means grouping by year, month, day, and hour.

One way to do this would be to group by the formatted date only up to the hour:

.collect(Collectors.groupingBy(x -> DateTimeFormatter.ofPattern("yyyyMMddHH").format(x));

Alternatively, truncate each date to hours using truncatedTo:

.collect(Collectors.groupingBy(x -> x.truncatedTo(ChronoUnit.HOURS));
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

You can try grouping it by both the day and the hour:

objects().collect(
      groupingBy(x -> x.getDate().get(ChronoField.DAY_OF_YEAR),
       groupingBy(x -> x.getDate().get(ChronoField.HOUR_OF_DAY))));
Konrad Höffner
  • 11,100
  • 16
  • 60
  • 118