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 楼答案
实际上,您很少关心结果是否应该存储到
ArrayList
或任何其他List
实现中。因此,使用Collectors.toList()
而不是Collectors.toCollection(ArrayList::new)
可能更好。此外,使用在这种情况下,你可以简单地写
toList()
使用
Random.ints(long, int, int)
作为源,您可以在单个调用中生成0..10000
范围内的10个随机数。把所有东西放在一起,你会得到:注意,根据这些数字的进一步使用,您可能会考虑将它们存储到数组中:
这样不仅更短,而且更高效(CPU和内存方面),因为不需要装箱