tl;dr
List
.of( "2021-07-01", "2021-08-20", "2021-08-25", "2021-09-05", "2022-01-06", "2022-06-07" )
.stream()
.map( input -> LocalDate.parse( input ) ) // Parse each element as a `LocalDate` object, for a new stream.
.collect(
Collectors.groupingBy( date ->
YearMonth :: from , // Extract a `YearMonth` from each `LocalDate` as the key.
Collectors.counting() // Count occurrences.
)
) // Return a `Map`.
Details
Make example data.
List< String > inputs = List.of( "2021-07-01", "2021-08-20", "2021-08-25", "2021-09-05", "2022-01-06", "2022-06-07" );
Make a stream of those inputs. Parse each element as a LocalDate
object, for a new stream. Produce a key-value Map < YearMonth , Integer >
object by extracting a YearMonth
from each LocalDate
as the key, and summing one as a count of occurrences for the value.
Map< YearMonth , Integer > monthCounts =
inputs
.stream()
.map( input -> LocalDate.parse( input ) ) // Parse each element as a `LocalDate` object, for a new stream.
.collect(
Collectors.groupingBy( date ->
YearMonth :: from , // Extract a `YearMonth` from each `LocalDate` as the key.
Collectors.counting() // Count occurrences.
)
) // Return a `Map`.
;
See this code run live at Ideone.com.
{2021-09=1, 2021-08=2, 2021-07=1, 2022-06=1, 2022-01=1}
Sort by year-month: NavigableMap
You might want to keep the entries in your resulting map sorted by the YearMonth
keys. If so:
- Change your declared map type from
Map
to NavigableMap
interface.
- Add an argument for
TreeMap :: new
to instantiate an objecting implementing NavigableMap
.
NavigableMap < YearMonth, Long > monthCounts =
inputs
.stream()
.map( input -> LocalDate.parse( input ) )
.collect(
Collectors.groupingBy(
YearMonth :: from ,
TreeMap::new,
Collectors.counting()
)
);