title: Java 8 Stream.findAny() vs finding a random element in the stream
body: <p>In my Spring application, I have a Couchbase repository for a document type of <code>QuoteOfTheDay</code>.  The document is very basic, just has an id field of type UUID, value field of type String and created date field of type Date.</p>
  
  <p>In my service class, I have a method that returns a random quote of the day.  Initially I tried simply doing the following, which returned an argument of type <code>Optional&lt;QuoteOfTheDay&gt;</code>, but it would seem that findAny() would pretty much always return the same element in the stream.  There's only about 10 elements at the moment.</p>
  
  <pre><code>public Optional&lt;QuoteOfTheDay&gt; random() {
      return StreamSupport.stream(repository.findAll().spliterator(), false).findAny();
  }
  </code></pre>
  
  <p>Since I wanted something more random, I implemented the following which just returns a <code>QuoteOfTheDay</code>.</p>
  
  <pre><code>public QuoteOfTheDay random() {
      int count = Long.valueOf(repository.count()).intValue();
  
      if(count &gt; 0) {
          Random r = new Random();
  
          List&lt;QuoteOfTheDay&gt; quotes = StreamSupport.stream(repository.findAll().spliterator(), false)
                  .collect(toList());
  
          return quotes.get(r.nextInt(count));
      } else {
          throw new IllegalStateException("No quotes found.");
      }
  }
  </code></pre>
  
  <p>I'm just curious how the <code>findAny()</code> method of Stream actually works since it doesn't seem to be random.</p>
  
  <p>Thanks.</p>