使用Java 8 Streams API对整数列表进行随机播放 [英] Shuffle a list of integers with Java 8 Streams API

查看:89
本文介绍了使用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)

我怀疑在流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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆