Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 435
SneakyShrike Avatar asked Jan 10 '18 17:01

SneakyShrike


2 Answers

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());
like image 83
Juan Carlos Mendoza Avatar answered Sep 27 '22 23:09

Juan Carlos Mendoza


Streams are really not suitable for this job. Like, really really.

A better way is to use Collections.shuffle:

// you can replace this with however you want to populate your array. 
// You can do a for loop that loops from 1 to 9 and add each number.
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
Collections.shuffle(list);
// now "list" is in a random order

EDIT:

Now that I know you have a custom list, here's another approach. Write two methods that converts your custom list to a normal ArrayList and the other way round as well. Convert your custom list to an ArrayList, do the shuffle, and convert it back.

Just for fun, Stream, when paralleled, can kind of produce stuff in a random order, but not really.

I ran this code for 10 times:

IntStream.range(1, 10).parallel().forEach(System.out::print);

And here were the output:

347195628
342179856
832497165
328194657
326479581
341287956
873629145
837429156
652378914
632814579
like image 21
Sweeper Avatar answered Sep 27 '22 23:09

Sweeper