JosephG
JosephG

Reputation: 3253

Randomly select an item from a list

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

Answers (5)

Mattia Ferigutti
Mattia Ferigutti

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

Oleksandr Yefymov
Oleksandr Yefymov

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

veeyikpong
veeyikpong

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

user2763281
user2763281

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

Jon Lin
Jon Lin

Reputation: 143946

Something like this?

Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));

Upvotes: 114

Related Questions