Hi Daniel,
what about providing List.getRandom() as an extension method [1] in your
projects?
Best regards
Johannes
[1]
https://github.com/manifold-systems/manifold/blob/master/manifold-deps-parent/manifold-ext/README.md
On 23/08/2025 21:36, Daniel Tavares wrote:
Dear OpenJDK community,
I’d like to propose the addition of a |getRandom()| default method to
the |java.util.List| interface.
As a Java developer with over 15 years of experience, I’ve often found
myself needing to retrieve a random element from a list. While this
can be achieved using |ThreadLocalRandom| or by shuffling the list,
these approaches require boilerplate code and are not immediately
intuitive—especially for newcomers to the language.
*Motivation*
Retrieving a random element from a list is a common task in many domains:
* Games and simulations
* Educational tools
* Random sampling in data processing
* Lightweight testing scenarios
Adding a default method like |getRandom()| would improve readability
and reduce friction for developers, particularly those learning Java
or working on rapid prototyping.
*Proposed Method*
default T getRandom() {
if (isEmpty()) return null;
int index = ThreadLocalRandom.current().nextInt(size());
return get(index);
}
Alternatively, the method could throw |NoSuchElementException| if the
list is empty, depending on what the community considers more idiomatic.
*Benefits*
* *Improved developer experience*: Simplifies a common use case.
* *Better readability*: Expresses intent directly.
* *Minimal impact*: Can be added as a default method without
breaking existing implementations.
* *Alignment with modern Java*: Leverages default methods introduced
in Java 8.
I understand that additions to core interfaces are considered
carefully, and I welcome feedback on whether this idea aligns with the
design philosophy of the Java Collections Framework.
Thank you for your time and consideration.
Best regards,
Daniel Perin Tavares
Curitiba, Brazil