In my Spring application, I have a Couchbase repository for the QuoteOfTheDay document QuoteOfTheDay . The document is very simple, just has an id field of type UUID, a value field of type String and created a date field of type Date.
In my service class, I have a method that returns a random quote of the day. At first I tried just to do the following, which returned an argument of type Optional<QuoteOfTheDay> , but it would seem that findAny () almost always returns the same element in the stream. At the moment, only about 10 elements.
public Optional<QuoteOfTheDay> random() { return StreamSupport.stream(repository.findAll().spliterator(), false).findAny(); }
Since I wanted something more random, I implemented the following, which simply returns QuoteOfTheDay .
public QuoteOfTheDay random() { int count = Long.valueOf(repository.count()).intValue(); if(count > 0) { Random r = new Random(); List<QuoteOfTheDay> quotes = StreamSupport.stream(repository.findAll().spliterator(), false) .collect(toList()); return quotes.get(r.nextInt(count)); } else { throw new IllegalStateException("No quotes found."); } }
I'm just wondering how the findAny() Stream method works, since it doesn't seem random.
Thanks.
source share