Main Tutorials

Java : Return a random item from a List

java-random-number

Normally, we are using the following ways to generate a random number in Java.

1. ThreadLocalRandom (JDK 1.7)


//Generate number between 0-9
int index = ThreadLocalRandom.current().nextInt(10);	

2. Random()


//Generate number between 0-9
Random random = new Random();
int index = random.nextInt(10);

3. Math.random()


//Generate number between 0-9
int index = (int)(Math.random()*10);
Note

1. For single thread, there is not much performance difference, just pick whatever you want.

2. For multiple threads, it’s recommended to use ThreadLocalRandom. Random is thread safe, but if multiple threads use the same instance of Random, it leads high contention (multiple threads to keep accessing the same “random” generator method) and it kills performance. ThreadLocalRandom solve this by generating a Random instance per thread.

Read this ThreadLocalRandom JavaDoc.

In this tutorial, we will show you how to use above methods to get a random item from a List.

1. ThreadLocalRandom

ThreadLocalRandom example to get a random item from an ArrayList.

ThreadLocalRandomExample.java

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);
	    
	}
	
}

Output. The result will be different each time program is executed.


Index :2
30

Index :4
50

Index :4
50

Index :3
40

Index :4
50

Index :0
10

Index :2
30

Index :1
20

Index :2
30

Index :4
50

2. Ramdom()

Random example to get a random item from an ArrayList.

RandomExample.java

package com.mkyong;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomExample {

	private Random random = new Random();
	
	public static void main(String[] args) {

		List<String> list = new ArrayList<String>();
		list.add("Apple");
		list.add("Boy");
		list.add("Cat");
		list.add("Dog");
		list.add("Elephant");

		RandomExample obj = new RandomExample();
		for(int i = 0; i < 10; i++){
			System.out.println(obj.getRandomList(list));
		}
		
	}

	public String getRandomList(List<String> list) {

	    //0-4
	    int index = random.nextInt(list.size());
	    System.out.println("\nIndex :" + index );
	    return list.get(index);
	    
	}
	
}

Output


Index :3
Dog

Index :1
Boy

Index :2
Cat

Index :2
Cat

Index :4
Elephant

Index :1
Boy

Index :2
Cat

Index :0
Apple

Index :0
Apple

Index :3
Dog

3. Math.random()

Math.random() example to get a random item from an ArrayList.

MathRandomExample.java

package com.mkyong;

import java.util.ArrayList;
import java.util.List;

public class MathRandomExample {

	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);

		MathRandomExample obj = new MathRandomExample();
		for(int i = 0; i < 10; i++){
			System.out.println(obj.getRandomList(list));
		}
		
	}

	public int getRandomList(List<Integer> list) {

	    //Math.random() = greater than or equal to 0.0 and less than 1
            //0-4
	    int index = (int)(Math.random()*list.size());
	    System.out.println("\nIndex :" + index );
	    return list.get(index);
	    
	}
	
}

References

  1. Concurrent Random in Java SE 7
  2. Reddit : Avoid Random. Use new ThreadLocalRandom from Java7
  3. Using ThreadLocalRandom for random number generation

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Robeto Thompson
5 years ago

And what if I don’t want the index, just the number.
I did that to generate numbers from 1 to 60 and get only six returned
but I couldn’t get ride of the index.

int num = 1;
List list = new ArrayList();

while (num <= 60) {
list.add(num);
num++;
}
ThreadLocalRandomExample obj = new ThreadLocalRandomExample();
for(int i = 1; i < 6; i++) {…..

Nix
1 year ago

I understand whatever returned from the list wouldn’t be unique values when run in a loop. Right?

Gilbert Alcantara
8 years ago

Is very good your tutorial, and thanks from Domincan Republic

marcel
8 years ago

Hi, how would I do it if I want to return 3 random items? thanks.

Mridul
8 years ago

I really like your Tutorials. Thanks for all the effort. I slightly parameterized this code for reuse.

public T retrieveRandomItemFromList(List t){

int index = ThreadLocalRandom.current().nextInt(t.size());

return t.get(index);

}

cu Li`
9 years ago

I using RandomUtils of apache lang

kpagcha
9 years ago

I think it would have been way more interesting to make performance tests instead of showing obvious outputs.

jruo
9 years ago
Reply to  kpagcha

i think current example is more than enough considering the title

Leonardo
9 years ago
Reply to  kpagcha

I agree, which one is the best?