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

Chen Liang chen.l.liang at oracle.com
Mon Aug 25 15:22:18 UTC 2025


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


More information about the core-libs-dev mailing list