How to get random range number in set

后端 未结 3 1642
你的背包
你的背包 2021-01-21 12:26

I have 100 record [1 -> 100], i want get random 50 record in this, how to do in java? Thanks.

3条回答
  •  星月不相逢
    2021-01-21 13:07

    You can get 50 random values.

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

    You can get 50 unique values in a random order using shuffle.

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

提交回复
热议问题