0 Replies - 5743 Views - Last Post: 04 April 2014 - 11:55 AM

#1 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1424
  • Posts: 3,166
  • Joined: 05-April 11

Java 8 - Stream of random LocalDate

Post icon  Posted 04 April 2014 - 11:55 AM

The following snippet combines the new Time- and Stream API found in Java 8
Combining the two APIs provide us with some extremely powerful and elegant solutions

Choose two LocalDates and generate all the random LocalDates you want between them with the following snippet!
import java.time.LocalDate;
import java.time.Month;
import java.util.PrimitiveIterator.OfLong;
import java.util.Random;
import java.util.stream.Stream;

public class RandomDateTest {

	public static void main(String[] args) {
		LocalDate start = LocalDate.of(1980, Month.JANUARY, 1); //Inslusive
		LocalDate end = LocalDate.of(2013, Month.JANUARY, 1); //Exclusive
		//Stream generating LocalDates between start and end
		Stream<LocalDate> generator = createDateGeneratorBetween(start, end);
		//Take 5 random LocalDates and print them
	private final static Random random = new Random();
	public static Stream<LocalDate> createDateGeneratorBetween(final LocalDate start, final LocalDate end) {
		//Iterator giving a random day (as long) between start and end since epoch
		final OfLong daySupplier = random.longs(start.toEpochDay(), end.toEpochDay()).iterator();
			//Return an infinite stream
			//Takes a random day since epoch, and converts it to a LocalDate
			Stream.generate(() -> {
				return LocalDate.ofEpochDay(daySupplier.next());

Is This A Good Question/Topic? 1
  • +

Page 1 of 1