As @Ole V.V. has pointed out in the comments, it seems like strings in your array are comprised of the year like 2012
and the day of the year like 001
.
If so, it would be match more convenient to convert this data into LocalDate
than operating with it as if it's a plain string.
To parse these row strings into LocalDate
you need to create a DateTimeFormatter
using the static method ofPattern()
.
A string pattern that corresponds to the sample data will be the following:
yyyyDDD
y
- stands for year;
D
- day of the year.
For more information see
So to filter out dates having a particular year, firstly we need to parse every string using LocalDate.parse()
by passing the string and the formatter as arguments, and then extract year from each date by applying getYear()
:
String [] num = {"2012001", "2003001", "2003002"};
int targetYear = 2003;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyDDD");
List<LocalDate> dates = Arrays.stream(num)
.map(date -> LocalDate.parse(date, formatter))
.filter(date -> date.getYear() == targetYear)
.collect(Collectors.toList());
System.out.println(dates);
Output:
[2003-01-01, 2003-01-02]