Java - Create an IntStream with a given range, then randomise each element using a map function

SneakyShrike :

So I've created an IntStream where I give it a range of 1 - 9. I would like to be able to use the map function to take each element in the given range (1-9) and randomise each one.

Essentially I would like to stream the numbers 1 - 9 in a different order each time the program is ran. (I'm open to other ideas, but it has to be using streams).

I've heard about using Java's Random class but i'm not sure how i would implement that over a map of each element.

I've tried doing this but there are errors:

 IntStream.range(1, 9).map(x -> x = new Random()).forEach(x -> System.out.println(x));

Any help would be appreciated.

Juan Carlos Mendoza :

It can be done this way too using Random.ints:

new Random().ints(1,10)
        .distinct()
        .limit(9)
        .forEach(System.out::println);

Output:

9 8 4 2 6 3 5 7 1

EDIT

If you need a Stream with the values then do this:

Stream<Integer> randomInts = new Random().ints(1, 10)
        .distinct()
        .limit(9)
        .boxed();

If you need a List with the values then do this:

List<Integer> randomInts = new Random().ints(1, 10)
        .distinct()
        .limit(9)
        .boxed()
        .collect(Collectors.toList());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=472301&siteId=1