Assign random integer numbers to an ArrayList using stream

I came up with this:

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));

Since I am pretty new to streams: Is there something more elegant i.e. shorter while at least equally readable (still using streams)?

Upvotes: 1

Views: 1225

Answers (2)

ashiquzzaman33
ashiquzzaman33

Reputation: 5741

More elegant with shorter and more readable using java.util.Random and IntStream

Random random = new Random();
random.ints(10, 0, 10000).boxed().forEach(randomIntegers::add);

Upvotes: 1

Tagir Valeev
Tagir Valeev

Reputation: 100279

You're rarely actually care whether the result should be stored into ArrayList or any other List implementation. So probably it's better to use Collectors.toList() instead of Collectors.toCollection(ArrayList::new). Furthermore, it's common practice to use

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

In this case you can write simply toList().

Using Random.ints(long, int, int) as source, you can generate 10 random numbers in the range of 0..10000 in the single call. Putting everything together, you will get:

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

Note that depending on further usage of these numbers, you may probably consider storing them into array instead:

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

This way it's not only shorter, but also more efficient (both CPU and memory-wise) as does not require the boxing.

Upvotes: 2

Related Questions