public static int getRandom(int[] array) {
    int rnd = new Random().nextInt(array.length);
    return array[rnd];
}
Answer from Chris Dennett on Stack Overflow
🌐
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 (int i = 0; i < numberOfElements; i++) { int randomIndex = rand.nextInt(givenList.size()); String randomElement = givenList....
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
Picking a random item from an array of strings in java - Stack Overflow
I have some arrays containing Strings and I would like to select randomly an item from each array. How can I accomplish this? Here are my arrays: static final String[] conjunction = {"and", "or",... More on stackoverflow.com
🌐 stackoverflow.com
September 12, 2023
java - Retrieving a random item from ArrayList - Stack Overflow
I'm learning Java and I'm having a problem with ArrayList and Random. I have an object called catalogue which has an array list of objects created from another class called item. I need a method in More on stackoverflow.com
🌐 stackoverflow.com
java - Random element from string array - Stack Overflow
-2 How do you make the computer select random elements from an array? More on stackoverflow.com
🌐 stackoverflow.com
August 13, 2024
🌐
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() ...
🌐
TutorialsPoint
tutorialspoint.com › article › java-program-to-generate-a-random-number-from-an-array
Java program to generate a random number from an array
November 4, 2024 - Now, we will get a random number from array using new Random() which creates a new instance of the random class. The nextInt(arr.length) generates a random integer from 0 to the length of the array.
🌐
Coderanch
coderanch.com › t › 676314 › java › Choose-random-element-array
Choose random element from array (Beginning Java forum at Coderanch)
February 17, 2017 - Assuming you meant "couldn't" (I do that all the time, by the way) here is how you would pass an ArrayList (or anything) into a method: ... I tried using what you wrote but its not working for me i get a compile error. i also had to add static to the methods or i get compile error. ... \FinalLottery.java:11: error: cannot find symbol populatePool(pool); ^ symbol: method populatePool(List<String>) location: class FinalLottery Note: G:\FinalLottery.java uses unchecked or unsafe operations.
🌐
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[].
🌐
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 - When // applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically // encounter much less overhead and contention. private static void getRandomInteger() { int crunchifyInteger = ThreadLocalRandom.current().nextInt(1, 50); log("RandomInteger: " + crunchifyInteger); } private static void getRandomDouble() { double crunchifyDouble = ThreadLocalRandom.current().nextDouble(1, 250); log("RandomDouble: " + crunchifyDouble); } public static String getRandomCompany() { ArrayList<String> companyName = new ArrayList<String>(); companyName.add("Google");
Find elsewhere
🌐
Quora
quora.com › How-do-I-pick-up-a-random-string-from-an-array-of-strings-in-Java
How to pick up a random string from an array of strings in Java - Quora
July 23, 2025 - You only need to generate a random number that acts as the index value for String array. You can generate random value using Random class defined in java.util package. [code]import java.util.Random; public class RandomStringFromArray { public ...
🌐
YouTube
youtube.com › asim code
How to randomly pick an element from an array in Java - YouTube
In this video we will learn how to randomly pick an element from an array in Java. Please subscribe to support Asim Code!https://www.youtube.com/channel/UC2w...
Published   November 5, 2021
Views   8K
🌐
ExamTray
examtray.com › java › java-program-how-print-random-element-or-index-array-arraylist
Java Program: How to Print or Get or Find a Random Element of An Array, ArrayList | ExamTray
July 12, 2025 - It is programmers need to choose or select or get or find a random element or number or string and a random index of an Array or ArrayList in Java. Let us explore Math.random() method with examples. The same code can be used to implement a Lottery Draw to pick a random contestant from a list ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › randomly-select-items-from-a-list-in-java
Randomly Select Items from a List in Java - GeeksforGeeks
July 11, 2025 - // Randomly select an element from a list import java.util.ArrayList; import java.util.List; import java.util.Random; public class Geeks { public static void main(String[] args) { // creating a list of integer type List<Integer> l = new ArrayList<>(); l.add(10); l.add(20); l.add(30); l.add(40); l.add(50); Geeks o = new Geeks(); // take a random element from list and print them System.out.println("Random Element: " + o.getRandomElement(l)); } // Function select an element base on index // and return an element public int getRandomElement(List<Integer> l) { Random r = new Random(); return l.get(r.nextInt(l.size())); } } Output ·
🌐
Coderanch
coderanch.com › t › 400428 › java › selecting-random-elements-array
selecting random elements from an array (Beginning Java forum at Coderanch)
August 3, 2022 - Hi I am sure this is really simple but I cannot work it out, although I have been searching the internet and books on Java I have the following array and I want to be able to select a random element from it each time the method is called: I just cannot think of a for loop to do this, so that ...
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 239268 › randomly-select-elements-from-array
java - Randomly select elements from array [SOLVED] | DaniWeb
May 21, 2023 - You can also use Random.nextInt(int) for the random int. Keep in mind that the suggestions tendered so far will allow the chance that an element is selected multiple times. If you don't … — Ezzaral 2,714 Jump to Post · for(int i=0;i<100;i++){ keys_Array[i] = unsorted.get( random.nextInt(100) ); }
🌐
TutorialsPoint
tutorialspoint.com › generate-a-random-array-of-integers-in-java
Generate a random array of integers in Java
November 4, 2023 - Here we use the nextInt() method in a loop to get a random integer for each element. for (int i = 0; i < arr.length; i++) arr[i] = rd.nextInt(); Anvi Jain · Updated on: 2023-09-12T03:29:56+05:30 · 40K+ Views · Java - Math random() method Java ·
🌐
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, ... "Fang" You can get a random element from a List of elements by generating a random index within the size range of the List....
🌐
YouTube
youtube.com › kirupa
Picking a Random Item from an Array - YouTube
Using just a single line of code, learn how to randomly pick an item from an array.📄 Read article: https://www.kirupa.com/html5/picking_random_item_from_arr...
Published   April 30, 2017
Views   9K
🌐
Stack Overflow
stackoverflow.com › questions › 56726416 › how-do-you-make-the-computer-select-random-elements-from-an-array › 56726491
java - How do you make the computer select random elements from an array? - Stack Overflow
October 2, 2020 - You should generate a pseudo random int between 0 and array.length - 1 then return the value with that index n your array. You can use Random.nextInt() for that: Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and ...