我尝试使用 Streams API 将以下 Scala 行转换为 Java 8:
// Scala
util.Random.shuffle((1 to 24).toList)
为了用 Java 编写等价的代码,我创建了一个整数范围:
IntStream.range(1, 25)
我怀疑在stream API中找到了一个toList
方法,但是IntStream
只知道奇怪的方法:
collect(
Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner)
如何使用 Java 8 Streams API 打乱列表?
最佳答案
给你:
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);
打印:
[8, 1, 5, 3, 4, 2, 6, 9, 7]
关于java - 使用 Java 8 Streams API 打乱整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20058366/