使用 Java 8 Streams API 打乱整数列表

2023-11-23

我尝试使用 Streams API 将以下 Scala 行转换为 Java 8:

// Scala
util.Random.shuffle((1 to 24).toList)

为了用 Java 编写等效的代码,我创建了一系列整数:

IntStream.range(1, 25)

我怀疑找到一个toList流 API 中的方法,但是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);

Prints:

[8, 1, 5, 3, 4, 2, 6, 9, 7]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Java 8 Streams API 打乱整数列表 的相关文章

随机推荐