使用 Java 8 Streams API 打乱整数列表 [英] Shuffle a list of integers with Java 8 Streams API
本文介绍了使用 Java 8 Streams API 打乱整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用 Streams API 将以下 Scala 行转换为 Java 8:
I tried to translate the following line of Scala to Java 8 using the Streams API:
// Scala
util.Random.shuffle((1 to 24).toList)
为了在 Java 中编写等价物,我创建了一系列整数:
To write the equivalent in Java I created a range of integers:
IntStream.range(1, 25)
我怀疑在stream API中找到了toList
方法,但是IntStream
只知道奇怪的方法:
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)
如何使用 Java 8 Streams API 打乱列表?
How can I shuffle a list with 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 8 Streams API 打乱整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文