Proposal: Add getRandom() default method to java.util.List
Viktor Klang
viktor.klang at oracle.com
Sun Aug 24 16:18:13 UTC 2025
While I'm sympathetic to the use-case, I think adding such a method to List is the wrong move—you could equally argue that there should be a randomIterator(), a randomSet(), a randomAdd(). And it wouldn't be coherent with the specification of the List-methods to create a wrapper-type which would perform the randomization (i.e. that set(i, e) would add it at a random index rather than at i).
It's also important to note that we cannot presume to know what level of randomness is required by the developer, so a RandomGenerator would need to be provided.
One could, however, argue whether there should be a convenience-method on RandomGenerator named something akin to "<T, L extends List<? extends T> & RandomAccess> T nextElement(L list)" however the discoverability of said method would be less-than-ideal.
This leads me to conclude that it is arguably better as a static utility method in the developer's codebase, or inlining it at use-site. After all, it's half a line of code, presuming of course that the author has already checked for emptiness:
var e = list.get(rand.nextInt(list.size());
vs
public static <T, L extends List<? extends T> & RandomAccess> T randomElement(RandomGenerator rand, L list) {
if(list.isEmpty()) // Implicit null-check of list
throw new NoSuchElementException();
else
return list.get(rand.nextInt(list.size())); // Implicit null-check of rand
}
var e = randomElement(rand, list);
Cheers,
√
Viktor Klang
Software Architect, Java Platform Group
Oracle
________________________________
From: core-libs-dev <core-libs-dev-retn at openjdk.org> on behalf of Alan Bateman <alan.bateman at oracle.com>
Sent: Sunday, 24 August 2025 11:42
To: Daniel Tavares <cetr1n at gmail.com>; core-libs-dev at openjdk.org <core-libs-dev at openjdk.org>
Subject: Re: Proposal: Add getRandom() default method to java.util.List
On 23/08/2025 20:36, Daniel Tavares wrote:
:
Proposed Method
default T getRandom() {
if (isEmpty()) return null;
int index = ThreadLocalRandom.current().nextInt(size());
return get(index);
}
Add Lists that are mutable and support concurrent access to your list to think about. These implementations would need to be updated to implement this method, otherwise you risk getting IOOBE with the default method.
-Alan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20250824/93e1d55e/attachment-0001.htm>
More information about the core-libs-dev
mailing list