Saving the generated stream to an ArrayList
What I have to do is create an ArrayList of random numbers via stream.generate. The code below is my attempt to try and store it in an ArrayList, but it is of type "object". I figured that I need to somehow map it to int first, but I don't know how. The code doesn't work right now.
public ArrayList<Integer> createRandomList(ArrayList<Integer> list, int amount) {
ArrayList<Integer> a = Arrays.asList(Stream.generate(new Supplier<Integer>() {
@Override
public Integer get() {
Random rnd = new Random();
return rnd.nextInt(100000);
}
}).limit(amount).mapToInt.toArray());
}
+3
source to share
2 answers
You can use Collector:
return Stream.generate (() -> new Random().nextInt(100000))
.limit(amount)
.collect (Collectors.toList());
This will create List<Integer>
, but not necessarily ArrayList<Integer>
.
It would make more sense to create one instance of Random:
final Random rnd = new Random();
return Stream.generate (() -> rnd.nextInt(100000))
.limit(amount)
.collect (Collectors.toList());
+3
source to share