1
    //convert the comma separated numeric string into the  array of int. 
    public class HelloWorld
    {
      public static void main(String[] args)
      {
       // line is the input  which have the comma separated number
        String line = "1,2,3,1,2,2,1,2,3,";
       // 1 > split   
         String[] inputNumber =  line.split(",");
       // 1.1 > declare int array
         int number []= new int[10];
       // 2 > convert the String into  int  and save it in int array.
         for(int i=0; i<inputNumber.length;i++){
               number[i]=Integer.parseInt(inputNumber[i]);
         }
    }
}

Is it their any better solution of doing it. please suggest or it is the only best solution of doing it.

My main aim of this question is to find the best solution.

1
  • Note: this question has been cross-posted on Code Review. (That's OK, but please declare cross-posts as a courtesy to other users.) Commented Mar 8, 2016 at 19:23

3 Answers 3

16

Java 8 streams offer a nice and clean solution:

String line = "1,2,3,1,2,2,1,2,3,";
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();

Edit: Since you asked for Java 7 - what you do is already pretty good, I changed just one detail. You should initialize the array with inputNumber.length so your code does not break if the input String changes.

Edit2: I also changed the naming a bit to make the code clearer.

String line = "1,2,3,1,2,2,1,2,3,";
String[] tokens = line.split(",");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
    numbers[i] = Integer.parseInt(tokens[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I did not about java 8, Any solution related to java 7.
@PrabhatYadav I edited my solution but what you had is already pretty much the best you can do in Java 7
2

By doing it in Java 7, you can get the String array first, then convert it to int array:

String[] tokens = line.split(",");
int[] nums = new int[tokens.length];

for(int x=0; x<tokens.length; x++)
    nums[x] = Integer.parseInt(tokens[x]);

1 Comment

Hmm yes quite an innovative solution
1

Since you don't like Java 8, here is the Best™ solution using some Guava utilities:

int[] numbers = Ints.toArray(
        Lists.transform(
                Splitter.on(',')
                        .omitEmptyStrings()
                        .splitToList("1,2,3,1,2,2,1,2,3,"),
                Ints.stringConverter()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.