convert comma separated string to list without intermediate container

前端 未结 7 2025
误落风尘
误落风尘 2021-01-01 12:36

I need to convert comma separated string to list of integers. For example if I have following string

String numbersArray = \"1, 2, 3, 5, 7, 9,\";
         


        
7条回答
  •  醉梦人生
    2021-01-01 13:23

    I think below piece of code could be helpful for you.

    import java.util.Scanner;
    
    public class Solution {
        public static void main(String[] args) throws java.io.IOException {
            String numbersArray = "1, 2, 3, 5, 7, 9,";
            System.out.println(numbersArray);
            Scanner sc = new Scanner(numbersArray);
            sc.useDelimiter("(, *)*");
            try{
                while(true){
                    System.out.println(sc.nextInt());
                }
            } catch (Exception e) {
                System.out.println("reading is completed");
            }
        }
    }
    

    Instead of using System.out.println add it to the Integer list.

    Here we are not traversing through the complete list multiple times, instead we traverse only once and storing them in array.

提交回复
热议问题