I implemented the following class DateBucket that has a method called bucketize. This method returns a list of DateBucket where each DateBucket in the list is between the dates fromDate and toDate and uses bucketSize and bucketSizeUnit as steps to set the values of the from and to DateBucket variables.
class DateBucket {
final Instant from;
final Instant to;
public static List<DateBucket> bucketize(
ZonedDateTime fromDate,
ZonedDateTime toDate,
int bucketSize,
ChronoUnit bucketSizeUnit
) {
List<DateBucket> buckets = new ArrayList<>();
boolean reachedDate = false;
for (int i = 0; !reachedDate; i++) {
ZonedDateTime minDate = fromDate.plus(i * bucketSize, bucketSizeUnit);
ZonedDateTime maxDate = fromDate.plus((i + 1) * bucketSize, bucketSizeUnit);
reachedDate = toDate.isBefore(maxDate);
buckets.add(new DateBucket(minDate.toInstant(), maxDate.toInstant()));
}
return buckets;
}
}
As an example the following input:
fromDate -> 2020-12-07 00:00:00
toDate -> 2020-12-07 00:00:03
bucketSize -> 1
bucketSizeUnit -> ChronoUnit.SECONDS
Returns the following DateBucket list:
0. DateBucket(from = 2020-12-07 05:00:00, to = 2020-12-07 05:00:01)
1. DateBucket(from = 2020-12-07 05:00:01, to = 2020-12-07 05:00:02)
2. DateBucket(from = 2020-12-07 05:00:02, to = 2020-12-07 05:00:03)
3. DateBucket(from = 2020-12-07 05:00:03, to = 2020-12-07 05:00:04)
So, How can I refactor the bucketize method using the same logic but with Java 8 Streams?