Search code examples
javarandomint

What would be the shortest way to write/create an int[] with 3 unique random numbers using a stream in java?


I am currently using the following code:

Map<Integer, Integer> numbersMap = new HashMap<>();
return IntStream.generate(() -> (int)(10 * Math.random() + 1))
                .filter(i -> numbersMap.put(i, i) == null)
                .limit(3)
                .toArray();

For example, I am wondering if there is a way to do this without the use of a HashMap, since I am only using the keys.


Solution

  • IntStream.generate(() -> (int) (10 * Math.random() + 1))
             .distinct()
             .limit(3)
             .toArray();
    

    or

    ThreadLocalRandom.current().ints(1, 10 + 1)
                               .distinct()
                               .limit(3)
                               .toArray();