Proposal: Add getRandom() default method to java.util.List

Johannes Döbler jd at civilian-framework.org
Mon Aug 25 20:51:34 UTC 2025


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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20250825/55d53aab/attachment-0001.htm>


More information about the core-libs-dev mailing list