Two main ways.

  1. Use Random#nextInt(int):

    List<Foo> list = createItSomehow();
    Random random = new Random();
    Foo foo = list.get(random.nextInt(list.size()));
    

    It's however not guaranteed that successive n calls returns unique elements.

  2. Use Collections#shuffle():

    List<Foo> list = createItSomehow();
    Collections.shuffle(list);
    Foo foo = list.get(0);
    

    It enables you to get n unique elements by an incremented index (assuming that the list itself contains unique elements).


In case you're wondering if there's a Java 8 Stream approach; no, there isn't a built-in one. There's no such thing as Comparator#randomOrder() in standard API (yet?). You could try something like below while still satisfying the strict Comparator contract (although the distribution is pretty terrible):

List<Foo> list = createItSomehow();
int random = new Random().nextInt();
Foo foo = list.stream().sorted(Comparator.comparingInt(o -> System.identityHashCode(o) ^ random)).findFirst().get();

Better use Collections#shuffle() instead.

Answer from BalusC on Stack Overflow
Top answer
1 of 13
123

Two main ways.

  1. Use Random#nextInt(int):

    List<Foo> list = createItSomehow();
    Random random = new Random();
    Foo foo = list.get(random.nextInt(list.size()));
    

    It's however not guaranteed that successive n calls returns unique elements.

  2. Use Collections#shuffle():

    List<Foo> list = createItSomehow();
    Collections.shuffle(list);
    Foo foo = list.get(0);
    

    It enables you to get n unique elements by an incremented index (assuming that the list itself contains unique elements).


In case you're wondering if there's a Java 8 Stream approach; no, there isn't a built-in one. There's no such thing as Comparator#randomOrder() in standard API (yet?). You could try something like below while still satisfying the strict Comparator contract (although the distribution is pretty terrible):

List<Foo> list = createItSomehow();
int random = new Random().nextInt();
Foo foo = list.stream().sorted(Comparator.comparingInt(o -> System.identityHashCode(o) ^ random)).findFirst().get();

Better use Collections#shuffle() instead.

2 of 13
42

Most of the proposed solutions till now suggest either a full list shuffle or successive random picking by checking uniqueness and retry if required.

But, we can take advantage of the Durstenfeld's algorithm (the most popular Fisher-Yates variant in our days).

Durstenfeld's solution is to move the "struck" numbers to the end of the list by swapping them with the last unstruck number at each iteration.

Due to the above, we don't need to shuffle the whole list, but run the loop for as many steps as the number of elements required to return. The algorithm ensures that the last N elements at the end of the list are 100% random if we used a perfect random function.

Among the many real-world scenarios where we need to pick a predetermined (max) amount of random elements from arrays/lists, this optimized method is very useful for various card games, such as Texas Poker, where you a-priori know the number of cards to be used per game; only a limited number of cards is usually required from the deck.

public static <E> List<E> pickNRandomElements(List<E> list, int n, Random r) {
    int length = list.size();

    if (length < n) return null;

    //We don't need to shuffle the whole list
    for (int i = length - 1; i >= length - n; --i)
    {
        Collections.swap(list, i , r.nextInt(i + 1));
    }
    return list.subList(length - n, length);
}

public static <E> List<E> pickNRandomElements(List<E> list, int n) {
    return pickNRandomElements(list, n, ThreadLocalRandom.current());
}
Discussions

Is there a smart way to get UNIQUE random elements from a collection in Java?
This turns out to be one of those things that smart people spent a bit too long discussing. That's because you're effectively asking "how do I efficient create a 1:1 mapping from one number (a counter in your case) to another (a random permutation of those same numbers)," and that's a relevant question for encryption and a few other things. That means you're basically constructing a form of "Format-preserving encryption:" https://en.wikipedia.org/wiki/Format-preserving_encryption But that's a bit crazy, so might I suggest that you do one of two things: If the upper bound is fairly small (say, less than 10,000), make a list of all of the elements and then shuffle it. Now just use the numbers from the beginning to the end of the list in order. If the upper bound is quite large but you only need a few numbers (say less than 10% of the range), store a set of numbers you've already used and just generate another random number if you encounter a repetition. If the upper bound is quite large and you need a whole lot of random numbers, it's probably time to start thinking about block cipher algorithms or linear congruential generators. More on reddit.com
🌐 r/learnprogramming
9
1
January 30, 2023
java - Select N random elements from a List efficiently (without toArray and change the list) - Stack Overflow
As in the title, I want to use Knuth-Fisher-Yates shuffle algorithm to select N random elements from a List but without using List.toArray and change the list. Here is my current code: public List... More on stackoverflow.com
🌐 stackoverflow.com
March 25, 2016
Pick multiple random elements from a list in Java - Stack Overflow
That's a very good idea :) but keeping track of an alternate list of indexes can get a little tricky. But thank you anyway :) 2011-12-04T21:47:39.213Z+00:00 ... @waxwing Yeah, that would take a while :-) In general, if R, the desired number of random items, is greater than half list's length, ... More on stackoverflow.com
🌐 stackoverflow.com
March 22, 2017
java - How can I select random element from the list? - Stack Overflow
I am using java.util.LinkedList Is there any method that helps me with this? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Baeldung
baeldung.com › home › java › java list › java – get random item/element from a list
Java - Get Random Item/Element From a List | Baeldung
April 4, 2025 - It is quite straightforward: public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() { Random rand = new Random(); List<String> givenList = Arrays.asList("one", "two", "three", "four"); int numberOfElements = 2; for ...
🌐
Reddit
reddit.com › r/learnprogramming › is there a smart way to get unique random elements from a collection in java?
r/learnprogramming on Reddit: Is there a smart way to get UNIQUE random elements from a collection in Java?
January 30, 2023 -

Right now I'm using the Random class, which .nextInt(upperbound) provides me with random integers that can be used to index an ArrayList object. I want to get several random elements and want them to be unique, however.

I can come up with some solutions, but none of them are very elegant. Any ideas?

Edit: current solution is to remove the randomly selected element, but I also have to decrease the upperbound (myList.size() - i ) on each iteration of the for-loop.
I know that Pyhton has a function that picks n unique random elements from a list, is there anything similar in Java?

Top answer
1 of 6
3
This turns out to be one of those things that smart people spent a bit too long discussing. That's because you're effectively asking "how do I efficient create a 1:1 mapping from one number (a counter in your case) to another (a random permutation of those same numbers)," and that's a relevant question for encryption and a few other things. That means you're basically constructing a form of "Format-preserving encryption:" https://en.wikipedia.org/wiki/Format-preserving_encryption But that's a bit crazy, so might I suggest that you do one of two things: If the upper bound is fairly small (say, less than 10,000), make a list of all of the elements and then shuffle it. Now just use the numbers from the beginning to the end of the list in order. If the upper bound is quite large but you only need a few numbers (say less than 10% of the range), store a set of numbers you've already used and just generate another random number if you encounter a repetition. If the upper bound is quite large and you need a whole lot of random numbers, it's probably time to start thinking about block cipher algorithms or linear congruential generators.
2 of 6
3
An optimal choice is probably to 'shuffle' an int[], initially filled with a continuous sequence of values over the range you want, and then 'taking' from the array using an 'index'. Taking from the array in reverse will allow the 'index' to serve as a count of remaining values, a trivial stop-point to test against zero, and the index itself. Alternatively, you can fill a List (an ArrayList is the best option), with a continuous sequence of values over the range you want, and then use Collections.shuffle(list). Taking values from the end of the list will be the most optimal choice - eg Integer value = list.remove(list.size() - 1). Note: the method of randomisation for Collections.shuffle is documented in the Javadoc and would be trivial to apply to an int[].
🌐
TutorialsPoint
tutorialspoint.com › randomly-select-items-from-a-list-in-java
Randomly select items from a List in Java
May 16, 2023 - Define an object of class ?Random?. Now, declare an integer variable named ?noOfrndmElem? that will store the number of items to be selected. Create a for loop that will run till the ?noOfrndmElem? and select the items. import java.util.*; public class Randomly { public static void main(String[] args) { // Creating arraylist ArrayList<Integer> araylist = new ArrayList<Integer>(); // Adding elements in arraylist araylist.add(8); araylist.add(5); araylist.add(2); araylist.add(9); araylist.add(4); araylist.add(7); System.out.println("Elements of the list : "); // loop to iterate through elements
🌐
GeeksforGeeks
geeksforgeeks.org › java › getting-random-elements-from-arraylist-in-java
Getting Random Elements from ArrayList in Java - GeeksforGeeks
July 23, 2025 - Note: Each time the Math.random() method is called it generates a new random value however original order of elements in the ArrayList does not get disturbed. ... // Java program for Getting Random Elements // from ArrayList using Math.random() ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › randomly-select-items-from-a-list-in-java
Randomly Select Items from a List in Java - GeeksforGeeks
July 11, 2025 - Example: This example demonstrates how to select random element from a list without repetition by removing the selected items from the original list. ... // Select random elements from a // list without repetition import java.util.ArrayList; import java.util.List; import java.util.Random; public class Geeks { public static void main(String[] args) { List<Integer> l = new ArrayList<>(); l.add(10); l.add(20); l.add(30); l.add(40); l.add(50); Geeks o = new Geeks(); System.out.println("Random Elements: " + o.getRandomElements(l, 3)); } public List<Integer> getRandomElements(List<Integer> l, int totalItems) { Random r = new Random(); List<Integer> newList = new ArrayList<>(); for (int i = 0; i < totalItems; i++) { int randomIndex = r.nextInt(l.size()); newList.add(l.get(randomIndex)); l.remove(randomIndex); // Remove selected item } return newList; } }
Find elsewhere
🌐
Sololearn
sololearn.com › en › Discuss › 1950284 › how-do-i-get-a-random-item-from-a-list-in-java
How do I get a random item from a list in java? | Sololearn: Learn to code for FREE!
August 30, 2019 - If I did a ArrayList in java with a couple of words (Like "hello" "hey" "bye") and I wanted to make the computer take a random word from the list, how do I do that?
🌐
Crunchify
crunchify.com › java j2ee tutorials › in java how to get random element from arraylist and threadlocalrandom usage
In Java How to Get Random Element from ArrayList and ThreadLocalRandom Usage • Crunchify
January 29, 2023 - */ public class CrunchifyRandomFromArrayList { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { log("Loop # " + i + " : " + getRandomCompany()); } getRandomDouble(); getRandomInteger(); } // a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When // applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically // encounter much less overhead and contention.
🌐
Mkyong
mkyong.com › home › java › java : return a random item from a list
Java : Return a random item from a List - Mkyong.com
August 5, 2014 - ThreadLocalRandom example to get a random item from an ArrayList. ... package com.mkyong; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public class ThreadLocalRandomExample { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); ThreadLocalRandomExample obj = new ThreadLocalRandomExample(); for(int i = 0; i < 10; i++){ System.out.println(obj.getRandomList(list)); } } public int getRandomList(List<Integer> list) { //0-4 int index = ThreadLocalRandom.current().nextInt(list.size()); System.out.println("\nIndex :" + index ); return list.get(index); } }
🌐
Java Mex
javamex.com › tutorials › random_numbers › random_sample.shtml
How to pick a random sample from a list
An example implementation in Java goes something like this: public static <T> T[] pickSample(T[] population, int nSamplesNeeded, Random r) { T[] ret = (T[]) Array.newInstance(population.getClass().getComponentType(), nSamplesNeeded); int nPicked = 0, i = 0, nLeft = population.length; while (nSamplesNeeded > 0) { int rand = r.nextInt(nLeft); if (rand < nSamplesNeeded) { ret[nPicked++] = population[i]; nSamplesNeeded--; } nLeft--; i++; } return ret; }
🌐
CodeSpeedy
codespeedy.com › home › how to randomly select items from a list in java
How to randomly select items from a list in Java - CodeSpeedy
November 23, 2020 - There can be a situation when the user wants to select more than one random item, so his normal approach will be generating a random index using the nextInt() function of random class’s object and looping it till we get the desired number of elements. But in this case, the random index generated can be the same and there are possibilities of getting the same random items chosen again and again. Here, is a code depicting the same situation: import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Arrays; public class RandomItem { // main function public static void main(String[] args) { // create a list of Integer values.
🌐
StackHowTo
stackhowto.com › home › java › how to randomly select an item from a list in java
How to randomly select an item from a list in Java - StackHowTo
October 9, 2021 - To select multiple random items, the above method getRandomItem() can easily be called multiple times. //Not optimal! public static <T> List<T> getRandomItems(List<T> list, int count) { List<T> arr = new ArrayList<>(); for (int i = 0; i < count; i++) { arr.add(getRandomItem(list)); } return arr; }...
Top answer
1 of 7
7

You are probably looking for something like Resorvoir Sampling.

Start with an initial array with first k elements, and modify it with new elements with decreasing probabilities:

java like pseudo code:

E[] r = new E[k]; //not really, cannot create an array of generic type, but just pseudo code
int i = 0;
for (E e : list) {
   //assign first k elements:
   if (i < k) { r[i++] = e; continue; }
   //add current element with decreasing probability:
   j = random(i++) + 1; //a number from 1 to i inclusive
   if (j <= k) r[j] = e;
}
return r;

This requires a single pass on the data, with very cheap ops every iteration, and the space consumption is linear with the required output size.

2 of 7
5

If n is very small compared to the length of the list, take an empty set of ints and keep adding a random index until the set has the right size.

If n is comparable to the length of the list, do the same, but then return items in the list that don't have indexes in the set.

In the middle ground, you can iterate through the list, and randomly select items based on how many items you've seen, and how many items you've already returned. In pseudo-code, if you want k items from N:

for i = 0 to N-1
    if random(N-i) < k
        add item[i] to the result
        k -= 1
    end
end

Here random(x) returns a random number between 0 (inclusive) and x (exclusive).

This produces a uniformly random sample of k elements. You could also consider making an iterator to avoid building the results list to save memory, assuming the list is unchanged as you're iterating over it.

By profiling, you can determine the transition point where it makes sense to switch from the naive set-building method to the iteration method.

🌐
CodingNConcepts
codingnconcepts.com › java › generate-random-numbers-in-java
How to generate Random Numbers in Java - Coding N Concepts
May 21, 2023 - Let’s run the below code snippet, which prints the random user from the list every time:- List<String> users = List.of("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack"); Random random = new Random(); System.out.println(users.get(random.nextInt(users.size()))); // Prints random user "David" // Prints random user "George" // Prints random user "Charlie" Java Collections provide a built-in shuffle() method to shuffle the elements of a List.
🌐
Coderanch
coderanch.com › t › 676314 › java › Choose-random-element-array
Choose random element from array (Beginning Java forum at Coderanch)
February 17, 2017 - Change line 6 to match lines 2‑3 ... to get a List instead. Change the argument in line 5 and you can get your 7 lottery numbers ready‑made as an array:) ... Junilu Lacar wrote:. . . I believe the Collections.shuffle() algorithm actually does that under the covers for you. . . . Don't know about the algorithm, but Joshua Bloch suggests that shuffle() isn't random enough for 52 cards. Can't remember whether it is in Effective Java or Java Puzzlers, ...
🌐
javaspring
javaspring.net › blog › pick-multiple-random-elements-from-a-list-in-java
How to Pick Multiple Random Elements from a List in Java Without Duplicates — javaspring.net
The simplest way to pick random unique elements is to shuffle the list and then select the first k elements. Shuffling ensures a random order, and taking the first k elements guarantees no duplicates (since all positions are unique).
🌐
Coderanch
coderanch.com › t › 695754 › java › Picking-random-element-arrayList
Picking a random element from an arrayList [Solved] (Beginning Java forum at Coderanch)
June 25, 2018 - You wish to select something from the list but your codes seems to be adding something to the list. ... Nik Recort wrote:But here it doesn't seem to work. Why not? What happens? Indexing is the same in lists and arrays, you just call the get() method instead of using the array's indexer.