convert comma separated string to list without intermediate container

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

    This works, as long as the String ends in a comma, like your example.

     String numbersArray = "1, 2, 3, 14, 5,";
     List list = new ArrayList();
     for (int i = 0, j, n = numbersArray.length(); i < n; i = j + 1) {
         j = numbersArray.indexOf(",", i);
         list.add(Integer.parseInt(numbersArray.substring(i, j).trim()));
     }
    

    However, it's pretty useless, as on my machine it's about 2 times slower than the original.

    This next solution, on the other hand, is surprisingly fast. I tested it on lists of 50000 integers obtained using Math.abs(random.nextInt()) and it was about 4 times faster than the original.

    List list = new ArrayList();
    for (int i = 0, a = 0, n = numbersArray.length(); i < n; i++) {
        char c = numbersArray.charAt(i);
        if (c == ',') {
            list.add(a);
            a = 0;
        } else if (c != ' ') {
            a = a * 10 + (c - '0');
        }
    }
    

    And this is about twice as fast again:

    List list = new ArrayList();
    for (int i = 0, a = 0, n = numbersArray.length(); i < n; i++) {
        switch(numbersArray.charAt(i)) {
            case ',': list.add(a); a = 0; break;
            case ' ': break;
            case '0': a = a * 10; break;
            case '1': a = a * 10 + 1; break;
            case '2': a = a * 10 + 2; break;
            case '3': a = a * 10 + 3; break;
            case '4': a = a * 10 + 4; break;
            case '5': a = a * 10 + 5; break;
            case '6': a = a * 10 + 6; break;
            case '7': a = a * 10 + 7; break;
            case '8': a = a * 10 + 8; break;
            case '9': a = a * 10 + 9; break;
            default: throw new AssertionError();
        }
    }
    

提交回复
热议问题