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?
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
Set is unordered, so randomizing an unordered Collection doesn't make any logical sense. An ordered Set is ordered using a Comparator which means it has a fixed order, you can't shuffle it, that has no meaning as the order is determined by the Comparator or the compare() method.
You can do this: Create a List of 52 numbers. Fill it with 26 zeroes and 26 ones, and then use Collections. shuffle() to shuffle them in a random order.
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]
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