我正在尝试创建一个单词列表,并且我想随机选择一个单词在字符串中使用。这是我目前拥有的:
private List<String> words = new ArrayList<String>();
public void someMethod() {
words.addAll(Arrays.asList("string1", "string2", "string3");
for (String s : words) {
// What now? How would I pick a random string from the list
// Also, if I shouldn't loop through the words, please tell me
System.out.println(randomString);
}
}
最佳答案
您可以生成一个介于 0 和列表大小之间的随机 int
,然后获取该索引处的元素。
words.addAll(Arrays.asList("string1", "string2", "string3");
String randomString = words.get(ThreadLocalRandom.current().nextInt(0, words.size()));
ThreadLocalRandom.nextInt(origin, bound)
返回指定原点(包括)和指定边界(不包括)之间的伪随机 int 值。
关于java - 从列表中获取随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33070283/