Java-创建具有给定范围的IntStream,然后使用map函数将每个元素随机化 [英] Java - Create an IntStream with a given range, then randomise each element using a map function

查看:65
本文介绍了Java-创建具有给定范围的IntStream,然后使用map函数将每个元素随机化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我创建了一个IntStream,将其范围设置为1-9.我希望能够使用map函数来获取给定范围(1-9)中的每个元素,并对每个元素进行随机化处理.

So I've created an IntStream where I give it a range of 1 - 9. I would like to be able to use the map function to take each element in the given range (1-9) and randomise each one.

基本上,每次程序运行时,我都希望以不同的顺序传输数字1-9.(我对其他想法持开放态度,但必须使用流).

Essentially I would like to stream the numbers 1 - 9 in a different order each time the program is ran. (I'm open to other ideas, but it has to be using streams).

我听说过使用Java的Random类,但是我不确定如何在每个元素的映射上实现它.

I've heard about using Java's Random class but i'm not sure how i would implement that over a map of each element.

我尝试这样做,但是有错误:

I've tried doing this but there are errors:

 IntStream.range(1, 9).map(x -> x = new Random()).forEach(x -> System.out.println(x));

任何帮助将不胜感激.

推荐答案

也可以使用

It can be done this way too using Random.ints:

new Random().ints(1,10)
        .distinct()
        .limit(9)
        .forEach(System.out::println);

输出:

9 8 4 2 6 3 5 7 1

9 8 4 2 6 3 5 7 1

编辑

如果您需要带有值的 Stream ,请执行以下操作:

If you need a Stream with the values then do this:

Stream<Integer> randomInts = new Random().ints(1, 10)
        .distinct()
        .limit(9)
        .boxed();

如果您需要带有值的 List ,请执行以下操作:

If you need a List with the values then do this:

List<Integer> randomInts = new Random().ints(1, 10)
        .distinct()
        .limit(9)
        .boxed()
        .collect(Collectors.toList());

这篇关于Java-创建具有给定范围的IntStream,然后使用map函数将每个元素随机化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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