Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
deamon Avatar asked Nov 18 '13 21:11

deamon


People also ask

How many types of streams does Java 8 have?

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.

Can you shuffle a set in Java?

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.

How do you randomize a list of numbers in Java?

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.


1 Answers

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] 
like image 52
Andrey Chaschev Avatar answered Oct 22 '22 08:10

Andrey Chaschev