Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String array into an int Array in java

Tags:

java

I am new to java programming. My question is this I have a String array but when I am trying to convert it to an int array I keep getting

java.lang.NumberFormatException 

My code is

private void processLine(String[] strings) {     Integer[] intarray=new Integer[strings.length];     int i=0;     for(String str:strings){         intarray[i]=Integer.parseInt(str);//Exception in this line         i++;     } } 

Any help would be great thanks!!!

like image 503
Manoj I Avatar asked Jul 30 '11 06:07

Manoj I


People also ask

How do you convert an array of strings to int arrays in java?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.

Can we convert string to array in java?

Using toArray() MethodThe toArray() function of the List class can also be used to convert a string to array in Java. It takes a list of type String as the input and converts each entity into a string array.


2 Answers

Suppose, for example, that we have a arrays of strings:

String[] strings = {"1", "2", "3"}; 

With Lambda Expressions[1] [2] (since Java 8), you can do the next :

int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray(); 

This is another way:

int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray(); 

—————————
Notes
  1. Lambda Expressions in The Java Tutorials.
  2. Java SE 8: Lambda Quick Start

like image 107
Paul Vargas Avatar answered Oct 03 '22 18:10

Paul Vargas


To get rid of additional whitespace, you could change the code like this:

intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line 
like image 26
Sean Patrick Floyd Avatar answered Oct 03 '22 19:10

Sean Patrick Floyd