Search code examples
javadatetime

Java 8 Grouping Objects by HOUR


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?


Solution

  • 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));