简体   繁体   English

从列表中随机选择一个项目

[英]Randomly select an item from a list

How can I randomly select an item from a list in Java?如何从 Java 列表中随机选择一个项目? eg 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:如果您在 Kotlin 中编码,最简单的方法是编写:

val randomElement = listName.shuffled()[0]

or要么

val randomElement = listName.random()

I hope it'll help you :)我希望它会帮助你:)

For Kotlin, you can use对于 Kotlin,您可以使用

random()

defined in kotlin.collections在 kotlin.collections 中定义

For example, Assuming例如,假设

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM