41

How can I randomly select an item from a list in Java? e.g. I have

List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");

etc.... How can I randomly select from this list using the

Random myRandomizer = new Random();
Radiodef
  • 37,180
  • 14
  • 90
  • 125
JosephG
  • 3,111
  • 6
  • 33
  • 56
  • 1
    This question does not show any research effort and duplicate of http://stackoverflow.com/questions/124671/picking-a-random-element-from-a-set – gh. Sep 19 '12 at 02:21
  • 8
    @gh, your reference for duplicate is incorrect as you linked to randomly selecting from sets, not lists :) – James Oravec May 31 '14 at 15:56

5 Answers5

111

Something like this?

Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));
Rápli András
  • 3,869
  • 1
  • 35
  • 55
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • 7
    @Hamidreza well, in the OP's example, it would be `myRandomizer`. The `nextInt()` call should have made that obvious. – Jon Lin Nov 23 '14 at 18:04
  • 1
    This returns the first element of the list for me, every single time. –  May 09 '19 at 10:45
19

Clean Code:

List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
String random = list.get(new Random().nextInt(list.size()));
lopez.mikhael
  • 9,943
  • 19
  • 67
  • 110
user2763281
  • 331
  • 4
  • 10
  • 3
    Can you provide some context to your answer, that way future readers can learn how to apply it to their issues and not just in this situation. – Newd Jul 23 '15 at 15:39
3

Simple and generic solution, for retrieving random element from your collections:

public static <T> T getRandomListElement(List<T> items) {
    return items.get(ThreadLocalRandom.current().nextInt(items.size()));
}
Oleksandr Yefymov
  • 6,081
  • 2
  • 22
  • 32
1

If you're coding in Kotlin the simplest way is writing:

val randomElement = listName.shuffled()[0]

or

val randomElement = listName.random()

I hope it'll help you :)

Mattia Ferigutti
  • 2,608
  • 1
  • 18
  • 22
0

For Kotlin, you can use

random()

defined in kotlin.collections

For example, Assuming

val results = ArrayList<Result>() //Get the list from server or add something to the list
val myRandomItem = results.random()
veeyikpong
  • 829
  • 8
  • 20