<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div class="moz-cite-prefix">Hi Daniel,<br>
<br>
what about providing List.getRandom() as an extension method [1]
in your projects?<br>
<br>
Best regards<br>
Johannes<br>
<br>
[1]
<a class="moz-txt-link-freetext" href="https://github.com/manifold-systems/manifold/blob/master/manifold-deps-parent/manifold-ext/README.md">https://github.com/manifold-systems/manifold/blob/master/manifold-deps-parent/manifold-ext/README.md</a><br>
<br>
<br>
<br>
On 23/08/2025 21:36, Daniel Tavares wrote:<br>
</div>
<blockquote type="cite"
cite="mid:CABeNBo3Tic0vPG6RBDd+7QX49RM-L90Drh_D5QrHSZQPhWT+HQ@mail.gmail.com">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<div dir="ltr">
<p>Dear OpenJDK community,</p>
<p>I’d like to propose the addition of a <code>getRandom()</code>
default method to the <code>java.util.List</code> interface.</p>
<p>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 <code>ThreadLocalRandom</code>
or by shuffling the list, these approaches require boilerplate
code and are not immediately intuitive—especially for
newcomers to the language.</p>
<p><b>Motivation</b></p>
<p>Retrieving a random element from a list is a common task in
many domains:</p>
<ul>
<li>Games and simulations</li>
<li>Educational tools</li>
<li>Random sampling in data processing</li>
<li>Lightweight testing scenarios</li>
</ul>
<p>
</p>
<p>Adding a default method like <code>getRandom()</code> would
improve readability and reduce friction for developers,
particularly those learning Java or working on rapid
prototyping.</p>
<p><b>Proposed Method</b></p>
<p>default T getRandom() {<br>
if (isEmpty()) return null;<br>
int index = ThreadLocalRandom.current().nextInt(size());<br>
return get(index);<br>
}</p>
<p>Alternatively, the method could throw <code>NoSuchElementException</code>
if the list is empty, depending on what the community
considers more idiomatic.</p>
<p><b>Benefits</b></p>
<ul>
<li><strong>Improved developer experience</strong>: Simplifies
a common use case.</li>
<li><strong>Better readability</strong>: Expresses intent
directly.</li>
<li><strong>Minimal impact</strong>: Can be added as a default
method without breaking existing implementations.</li>
<li><strong>Alignment with modern Java</strong>: Leverages
default methods introduced in Java 8.</li>
</ul>
<p><br>
</p>
<p>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.</p>
<p>Thank you for your time and consideration.</p>
<p>Best regards,</p>
<p>
Daniel Perin Tavares<br>
Curitiba, Brazil</p>
</div>
</blockquote>
<br>
</body>
</html>