javascalajava-stream

Shuffle a list of integers with Java 8 Streams API


I tried to translate the following line of Scala to Java 8 using the Streams API:

// Scala
util.Random.shuffle((1 to 24).toList)

To write the equivalent in Java I created a range of integers:

IntStream.range(1, 25)

I suspected to find a toList method in the stream API, but IntStream only knows the strange method:

collect(
  Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner)

How can I shuffle a list with Java 8 Streams API?


Solution

  • Here you go:

    List<Integer> integers =
        IntStream.range(1, 10)                      // <-- creates a stream of ints
            .boxed()                                // <-- converts them to Integers
            .collect(Collectors.toList());          // <-- collects the values to a list
    
    Collections.shuffle(integers);
    
    System.out.println(integers);
    

    Prints:

    [8, 1, 5, 3, 4, 2, 6, 9, 7]