Java : I have a list of String which holds Date column data from database. I want the count of each month .
Say I have data : 2021-07-01 2021-08-20 2021-08-25 2021-09-05 2022-01-06 2022-06-07
I want to retrieve value 1 for July,2 for August, 1 for September, 1 for January, 1 for June .
How can I use stream API to achieve this? Or any other method to retrieve vthis data
CodePudding user response:
I wrote up a process to allow you to get your desired goal using Streams and Lambdas.
Parse your dates into an Array of LocalDates.
Define a Predicate for your criteria.
Filter your Stream using your Predicate and get the count().
String[] dates = { "2021-07-01", "2021-08-20", "2021-08-25", "2021-09-05", "2022-01-06", "2022-06-07" }; LocalDate[] localDates = new LocalDate[dates.length]; for(int i = 0; i < dates.length; i ){ localDates[i] = LocalDate.parse(dates[i]); } Predicate<LocalDate> month = localDate -> localDate.getMonth().equals(Month.AUGUST); long count = Arrays.stream(localDates).filter(month).count();
CodePudding user response:
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( date ) , // Extract a `YearMonth` from each `LocalDate` as the key.
Collectors.summingInt( date -> 1 ) // Count occurrences by adding one.
)
) // 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}
I imagine there is a better way to count occurrences than Collectors.summingInt
, but I don’t know.