manolo
manolo

Reputation: 311

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.

Upvotes: 2

Views: 67

Answers (1)

Andrew
Andrew

Reputation: 49646

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

or

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

Upvotes: 3

Related Questions