[英]Java Extract Random Values from Text File
I posted a question earlier regarding how to extract the first eight values from an external text file using Java. 我较早前发布了一个问题 ,关于如何使用Java从外部文本文件中提取前八个值。 The text file contains the first 1000 prime numbers and I have written a method to read the data from said text file. 文本文件包含前1000个质数,我已经编写了一种从所述文本文件读取数据的方法。
I would like to know how to extract eight values at random and apply the results to another method. 我想知道如何随机提取八个值并将结果应用于另一种方法。
Something along the lines of: 类似于以下内容:
read data from file;
select eight random numbers from file;
apply random numbers to method;
I am able to extract the first eight numbers (as explained by a number of answers to my previous question), however I am now looking to extract eight random values - how can I do this? 我能够提取前八个数字(如上一个问题的一些答案所解释),但是现在我正在寻找提取八个随机值-我该怎么做?
Thank you. 谢谢。
List<Long> numbers = new ArrayList<Long>();
// ...
while ((line = reader.readLine()) != null) {
numbers.add(Long.valueOf(number));
}
Collections.shuffle(numbers);
List<Long> eightRandomNumbers = numbers.subList(0, 8);
Pass it. 交上来。
someMethod(eightRandomNumbers);
Another way is: 另一种方法是:
List<Long> numbers = new ArrayList<Long>();
//here you create reader from your file
while ((line = reader.readLine()) != null) {
numbers.add(Long.valueOf(number));
}
Long[] selectedNumbers = new Long[8]();
Random r = new Random();
for(int i = 0; i < selectedNumbers.length; i++){
selectedNumbers[i] = numbers.get(r.nextInt(numbers.Size()));
}
//8 random numbers are in selectedNumbers array
The advantage if this solution is that it is a little more efective then BalusC's answer. 这种解决方案的优势在于,它比BalusC的答案更有效果。 You can replace array by List
of course 您可以通过课程List
替换数组
You don't need to add all the numbers to your internal list, though with 1000 numbers it doesn't essentially matter. 您不需要将所有数字都添加到内部列表中,尽管有1000个数字实际上并不重要。 Essentially what you do is this: 本质上,您要做的是:
In case it's of any help, I've written an article on this topic before with example code: see how to pick a random sample from a list . 如果有帮助,我之前已经通过示例代码写过一篇关于该主题的文章:查看如何从list中选择随机样本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.