This is usually how I accept an Array
from a user. I ask for the size, then loop and populate the Array
.
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int[] numbers = new int[N];
for (int n=0; n<N; n++){
numbers[n] = scan.nextInt();
}
I have been trying to learn java 8 and I noticed that the Random
class has a method now to create a stream. It is pretty easy now to declare a n-sized array with random numbers.
int[] randomNumbers = new Random().ints().limit(N).toArray();
What I have been trying to do is create an array doing something similar with either streams or lambda expressions but for user input. What I tried doing is creating an IntStream
, map the values to Scanner#nextInt
, then create an array.
int[] numbers = new IntStream().map(x -> scan.nextInt()).limit(N).toArray();
What I can do is something like this:
int[] numbers = new int[N];
Arrays.fill(numbers, 0);
numbers = Arrays.stream(numbers).map(x -> scan.nextInt()).toArray();
System.out.println(Arrays.toString(numbers));
But that still feels a bit redundant. Filling the array with some arbitrary number only to replace it in the next line.