convert comma separated string to list without intermediate container

前端 未结 7 2167
误落风尘
误落风尘 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

    If you are willing to use Google Guava ( https://code.google.com/p/guava-libraries/ ) , splitter is your friend

        List list = new ArrayList();
        for ( String s : Splitter.on(',').trimResults().omitEmptyStrings().split("1, 2, 3, 14, 5,") ) {
          list.add(Integer.parseInt(s)); 
        }
    

    or, you could use something similar to your original approach and:

    List list = new ArrayList();
    for (String s :"1, 2, 3, 5, 7, 9,".split(",") ) {
        list.add(Integer.parseInt(s.trim()));
    }
    

提交回复
热议问题