Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a generated stream into an ArrayList [duplicate]

What I'm supposed to do is create an ArrayList of random numbers via stream.generate. Code below is my attempt of trying to save it into an ArrayList, but it's of type "object". I figured I have to somehow map it into int first, but I don't know how. Code right now doesnt work.

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());
}
like image 678
Jan Avatar asked Jan 08 '23 01:01

Jan


1 Answers

You may use create the stream of ints directly from Random object using ints(...), box them using boxed() and use the collector to store the result:

return new Random().ints(amount, 0, 100000)
                   .boxed()
                   .collect(Collectors.toCollection(ArrayList::new));
like image 192
Tagir Valeev Avatar answered Jan 15 '23 08:01

Tagir Valeev