Home > Back-end >  Creating a list with sequential elements
Creating a list with sequential elements

Time:12-07

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)?

e.g. {"10:00:00", "10:00:02", "10:00:04", "10:00:06", "10:00:08", ......} 
{"10:05:00", "10:10:00", "10:15:00", "10:20:00", "10:25:00", ......} 
{"10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", ......} 

CodePudding user response:

You can make an IntStream with IntStream.range(start, endExclusive), then use .map() or .mapToObj() on the stream to map the values to something else. All values are sequential, so IntStream.range(0, 10) will yield a stream containing [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

CodePudding user response:

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)
  • Related