Here are the code snippets for classic (algorithmic) approach and the second one that uses java streams api:
// algorithmic approach
LocalDateTime[] times = Array.randomLocalDateTimes(5);
Array.print(times);
Map<Integer, Integer> counts = new HashMap<>();
for (LocalDateTime time : times) {
int hour = time.get(ChronoField.HOUR_OF_DAY);
int count = counts.getOrDefault(hour, 0);
counts.put(hour, count+1);
}
System.out.println(counts);
// java streams aproach
Map<Integer, Integer> counts2 = Arrays.stream(times)
.collect(Collectors.toMap(time -> time.get(ChronoField.HOUR_OF_DAY), hour -> 1, Integer::sum));
System.out.println(counts2);
// java streams for 30 minutes
Map<String, Integer> counts3 = Arrays.stream(times)
.collect(Collectors.toMap(time -> time.get(ChronoField.HOUR_OF_DAY) + ":" + (time.get(ChronoField.MINUTE_OF_HOUR) < 30 ? "00" : "30"),
interval -> 1,
Integer::sum));
System.out.println(counts3);
Output:
2022-10-25T18:06:14.245215, 2022-10-25T22:15:14.246607, 2022-10-25T19:29:14.246624, 2022-10-25T18:08:14.246635, 2022-10-25T10:21:14.246645
{18=2, 19=1, 22=1, 10=1}
{18=2, 19=1, 22=1, 10=1}
{10:00=1, 22:00=1, 19:00=1, 18:00=2}