Filling an int [] array from the console on 1 line using Lambda (java)

try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { Object[] test = Arrays.stream(br.readLine().split(" ")).map(string -> Integer.parseInt(string)).toArray(); System.out.println(Arrays.toString(test)); } catch (IOException E) { } 

So this code works, but it returns an array of type Object[] However, I want it to return an array of type int[] .

Does anyone have any idea how I can do this?

+5
source share
1 answer

to get an array of type int , not Object , you can use the mapToInt method.

 int[] test = Arrays.stream(br.readLine().split(" ")) .mapToInt(Integer::parseInt).toArray(); 

note that you can simplify your code by using the link in the mapToInt argument .

reading:

+6
source

All Articles