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 t
To perform a shuffle efficiently you need all the values in advance. You can use Collections.shuffle() after you have converted the stream to a list like you do in Scala.
If you're looking for a "streaming only" solution and a deterministic, merely "haphazard" ordering versus a "random" ordering is Good Enough, you can always sort your int
s by a hash value:
List<Integer> xs=IntStream.range(0, 10)
.boxed()
.sorted( (a, b) -> a.hashCode() - b.hashCode() )
.collect(Collectors.toList());
If you'd rather have an int[]
than a List<Integer>
, you can just unbox them afterwards. Unfortunately, you have go through the boxing step to apply a custom Comparator
, so there's no eliminating that part of the process.
List<Integer> ys=IntStream.range(0, 10)
.boxed()
.sorted( (a, b) -> a.hashCode() - b.hashCode() )
.mapToInt( a -> a.intValue())
.toArray();