Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read integers separated with whitespace into int[] array

I read line with

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); reader.readLine(); 

Example input is

1 4 6 32 5 

What is the fastest way to read the input and put it into an integer array int[] ?

I'm also looking for some one-line solution if possible.

like image 642
hsz Avatar asked Jan 31 '13 21:01

hsz


People also ask

How do you break an integer into an array?

To split a number into an array:Convert the number to a string. Use the Array. from() method to convert the string into an array of digits. Use the map() function to convert each string in the array to a number.


1 Answers

You could use Scanner:

Scanner scanner = new Scanner(System.in); List<Integer> list = new ArrayList<Integer>(); while (scanner.hasNextInt())   list.add(scanner.nextInt()); int[] arr = list.toArray(new int[0]); 

Until we have closures in java, this is probably the shortest you can get.

int[] arr = list.toArray(new int[0]); won't work because there's no conversion from Integer to int. You can't use int as a type argument for generics.

But yeah If you are working with Java 8 then you can use Stream API for it with the below code snippet(Better way of doing things).

int[] array = list.stream().mapToInt(i->i).toArray();

like image 163
Andrew Logvinov Avatar answered Oct 04 '22 10:10

Andrew Logvinov