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.
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());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With