Splitting String and put it on int array

后端 未结 8 1361
眼角桃花
眼角桃花 2020-11-28 14:03

I have to input a string with numbers ex: 1,2,3,4,5. That\'s a sample of the input, then I have to put that in an array of INT so I can sort it but is not working the way it

相关标签:
8条回答
  • 2020-11-28 14:57

    Java 8 offers a streams-based alternative to manual iteration:

    int[] intArray = Arrays.stream(input.split(","))
        .mapToInt(Integer::parseInt)
        .toArray();
    

    Be prepared to catch NumberFormatException if it's possible for the input to contain character sequences that cannot be converted to an integer.

    0 讨论(0)
  • 2020-11-28 15:00
    List<String> stringList = new ArrayList<String>(Arrays.asList(arr.split(",")));
    List<Integer> intList = new ArrayList<Integer>();
    for (String s : stringList) 
       intList.add(Integer.valueOf(s));
    
    0 讨论(0)
提交回复
热议问题