Reputation: 3253
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();
Upvotes: 42
Views: 93706
Reputation: 3738
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 :)
Upvotes: 1
Reputation: 6509
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()));
}
Upvotes: 6
Reputation: 867
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()
Upvotes: 0
Reputation: 341
Clean Code:
List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
String random = list.get(new Random().nextInt(list.size()));
Upvotes: 19
Reputation: 143946
Something like this?
Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));
Upvotes: 114