有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用流将随机整数分配给ArrayList

我想到了这个:

ArrayList<Integer> randomIntegers = new ArrayList<>();
randomIntegers = Stream.generate(Math::random).map(n -> n * 10000)
                                              .mapToInt(Double::intValue)
                                              .limit(10)
                                              .boxed()
                                              .collect(Collectors.toCollection(ArrayList::new));

因为我对streams很陌生:是否有更优雅的东西,比如更短的,同时至少具有同样的可读性(仍在使用streams)


共 (1) 个答案

  1. # 1 楼答案

    实际上,您很少关心结果是否应该存储到ArrayList或任何其他List实现中。因此,使用Collectors.toList()而不是Collectors.toCollection(ArrayList::new)可能更好。此外,使用

    import static java.util.stream.Collectors.*;
    

    在这种情况下,你可以简单地写toList()

    使用Random.ints(long, int, int)作为源,您可以在单个调用中生成0..10000范围内的10个随机数。把所有东西放在一起,你会得到:

    List<Integer> randomIntegers = new Random().ints(10, 0, 10000).boxed().collect(toList());
    

    注意,根据这些数字的进一步使用,您可能会考虑将它们存储到数组中:

    int[] randomIntegers = new Random().ints(10, 0, 10000).toArray();
    

    这样不仅更短,而且更高效(CPU和内存方面),因为不需要装箱