Java Create an IntStream with a given range, then randomize each element using the map function

So, I created IntStream, where I give it a range from 1 to 9. I would like to be able to use the map function to take each element in a given range (1-9) and randomize each one.

Essentially, I would like to pass the numbers 1 - 9 in a different order each time the program starts. (I am open to other ideas, but it should use streams).

I heard about using the Java Random class, but I'm not sure how to implement it on a map of each element.

I tried to do this, but there are errors:

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

Any help would be greatly appreciated.

+4
source share
3 answers

Random.ints:

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

:

9 8 4 2 6 3 5 7 1

Stream , :

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

List , :

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

. , .

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:

, , , . , ArrayList . ArrayList, .

, Stream, , , .

10 :

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

:

347195628
342179856
832497165
328194657
326479581
341287956
873629145
837429156
652378914
632814579
+5
public static void main(String[] args) {
    Random random = new Random(); 
    //infinite stream of integers between 1(inclusive) and 10(exclusive)
    IntStream intStream = random.ints(1, 10);
    //from the infinite stream get a stream of 9 random and distinct integers and print them        
    intStream.distinct().limit(9).forEach(System.out::println);
}
+3
source

Source: https://habr.com/ru/post/1691998/


All Articles