Using Java Stream to count occurrences of Dates in a list of items
To count you're looking for something like:
Map<Instant, Long> foundInstants = foundDates.stream()
.collect(Collectors.groupingBy(Date::toInstant, Collectors.counting()));
to add to that you could cut short those if..else
into :
ExtendedDataSeriesItem seriesItem =
new ExtendedDataSeriesItem(c.toInstant(), foundInstants.getOrDefault(c.toInstant(), 0L));
seriesItem.setSeriesType("singleDataPoint");
series.add(seriesItem);
and this goes by saying that you should at the same time look for migrating to LocalDateTime
and refrain from using Date
.
You can use groupingBy()
and then use the downstream collector counting()
.
Map<Date, Long> occurrances = dateList.stream().collect(
groupingBy(d -> yourTransformation(d), counting()));
It should be easy enough to create your DataSeriesItem
objects from that map.