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

Rob Spoor openjdk at icemanx.nl
Mon Aug 25 16:14:56 UTC 2025


The API says that it can return any element, but in practice it returns 
the first element. I've never seen it return any other element.

`list.parallelStream().findAny()` doesn't do a lot better. Some short 
testing shows that although it doesn't return the first element, it 
still always returns the same element.


On 25/08/2025 17:22, Chen Liang wrote:
> Hi Daniel, can you explain why `list.stream().findAny()` does not fulfill your needs? This also returns a random element and is also very concise.
> 
> -Chen Liang
> ________________________________
> From: core-libs-dev <core-libs-dev-retn at openjdk.org> on behalf of Daniel Tavares <cetr1n at gmail.com>
> Sent: Saturday, August 23, 2025 2:36 PM
> To: core-libs-dev at openjdk.org <core-libs-dev at openjdk.org>
> Subject: Proposal: Add getRandom() default method to java.util.List
> 
> 
> 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
> 



More information about the core-libs-dev mailing list