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();
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();
Something like this?
Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));
Clean Code:
List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
String random = list.get(new Random().nextInt(list.size()));
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()));
}
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 :)
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()