如何获取集合中的随机范围数

我有100条记录[1 – > 100],我想在这里随机获得50条记录,如何在java中做? 谢谢。

 Set set; List list = new ArrayList(set); Collections.shuffle(list); List random50 = list.subList(0, 50); 

您可以获得50个随机值。

 Random rand = new Random(); List ints = new ArrayList(); for(int i = 0; i < 50; i++) ints.add(rand.nextInt(100)+1); 

您可以使用随机播放以随机顺序获取50个唯一值。

 List ints = new ArrayList(); for(int i = 1; i <= 100; i++) ints.add(i); Collections.shuffle(ints); ints = ints.subList(0, 50); 

生成四位长唯一代码的唯一可靠方法。

我发现首先要声明4个整数变量,为它们分配1到9之间的随机数。

然后我将这些整数转换为字符串,将它们连接在一起,使它们形成一个四位长的字符串,然后将结果字符串转换为整数。

得到的四位随机整数存储在一个数组中。

“请注意!!我是java新手”

 import javax.swing.JOptionPane; public class Rund4gen { /** * @param args the command line arguments */ public static void main(String[] args) { // I begin by creating an array to store all my numbers String userInput = JOptionPane.showInputDialog("How many 4 digit long numbers would you like to generate?"); int input = Integer.parseInt(userInput); // Now lets convert user input to a string int[] passCode = new int[input]; // We need to loop as many time as the user specified for(int i = 0; i < input; i++){ // Here I declare my integer variables int one, two, three, four; // For each of the integer variable I assign a rundom number one = (int)Math.floor((Math.random()*9)+1); two = (int)Math.floor((Math.random()*9)+1); three = (int)Math.floor((Math.random()*9)+1); four = (int)Math.floor((Math.random()*9)+1); // I need to convert my digits into a string in order to join them String n1 = String.valueOf(one); String n2 = String.valueOf(two); String n3 = String.valueOf(three); String n4 = String.valueOf(four); // Once conversion is complete then I join them as follows String nV = n1+n2+n3+n4; // Once joined, I then need to convert the joined result into an integer int nF = Integer.parseInt(nV); // I then store the result in an array as follows passCode[i] = nF; } // Now I need to print each value in the array for(int c = 0; c < passCode.length; c++){ System.out.print(passCode[c]+"\n"); } // Finally I thank the user for participating or not //JOptionPane.showMessageDialog(null,"Thank you for participating"); System.exit(0); } 

}