Random without duplicate using stream and questions about sort Java

1942 views java

I am trying to get 8 random int using stream but the problem with the code below is that distinct() removes duplicate which will not give me 8 int if there was any duplicate.


1.Get 8 random int (no duplicate)

2.Add to List

3.Sort the first 7 int.

I know Collections.sort(winlist.subList(0, 6)); works for sorting but im trying to see if it can be done with just stream.

    new Random()
            .ints (8, 0, 64)
            .forEach (Integer -> System.out.print (Integer + "\n"));

answered question

1 Answer


Use an endless stream and limit it after the distinct operation.

new Random().ints(0, 64).distinct().limit(8).sorted().forEach(System.out::println);

posted this

Have an answer?


Please login first before posting an answer.