Is there an utility method in Java (perhaps stream()
)to generate list of sequential elements, such as time that increased by constant value (seconds, minutes, hours)?
bySeconds(Start_time="10:00:00" interval=2, count=100)=>{"10:00:00", "10:00:02", "10:00:04", "10:00:06", "10:00:08", ......}
byMinutes(Start_time="10:00:00", interval=5, count=100)=>{"10:05:00", "10:10:00", "10:15:00", "10:20:00", "10:25:00", ......}
byHours(Start_time="10:00:00", interval=1, count=100)=>{"10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", ......}
Yes Stream.iterate
is designed for this purpose. For example:
Stream.iterate(LocalTime.of(10, 5), Duration.ofMinutes(5)::addTo)
Will generate an infinite stream of times starting at 10:05 and increasing by 5 minutes. If you wanted a specific end point you could use Stream.limit
to get a certain number or either add a predicate to the Stream.iterate
or use Stream.takeWhile
to end at a certain point. To covert to a list, use Stream.toList
.
If you want the times converted to a specific string format then use a DateTimeFormatter
. For example to convert to the format in the example in your question:
.map(DateTimeFormatter.ISO_LOCAL_TIME::format)