1

I'm trying to use this method to get a random element from a stream. Why does it always print "9"?

I know I can use list.get(new Random().nextInt(list.size())) but I only want to use the Stream API, even though it may not be efficient. How can I do that?

Integer[] array = {1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14};
List<Integer> list = Arrays.asList(array);

Integer anyElement = list.stream()
        .parallel()
        .findAny()
        .get();
System.out.println(anyElement);
Laurel
  • 5,965
  • 14
  • 31
  • 57
xiaozhu
  • 31
  • 3
  • Adding "Collections.shuffle(list);" before the stream call will ensure a shuffle happens. And one more option is to add the Random find as an intermediate operation. Integer anyElement = list .parallelStream() .skip(new Random().nextInt(list.size())) .findAny() .get(); – Vijayan Kani Jun 05 '22 at 01:10
  • I use your method ,It was pretty much what I wanted. thank you!!! – xiaozhu Jun 06 '22 at 07:15

0 Answers0