Generating Unique Random Numbers in Java

后端 未结 21 2553
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  不知归路
    2020-11-21 07:54

    With Java 8+ you can use the ints method of Random to get an IntStream of random values then distinct and limit to reduce the stream to a number of unique random values.

    ThreadLocalRandom.current().ints(0, 100).distinct().limit(5).forEach(System.out::println);
    

    Random also has methods which create LongStreams and DoubleStreams if you need those instead.

    If you want all (or a large amount) of the numbers in a range in a random order it might be more efficient to add all of the numbers to a list, shuffle it, and take the first n because the above example is currently implemented by generating random numbers in the range requested and passing them through a set (similarly to Rob Kielty's answer), which may require generating many more than the amount passed to limit because the probability of a generating a new unique number decreases with each one found. Here's an example of the other way:

    List range = IntStream.range(0, 100).boxed()
            .collect(Collectors.toCollection(ArrayList::new));
    Collections.shuffle(range);
    range.subList(0, 99).forEach(System.out::println);
    

提交回复
热议问题