Search code examples
javastringlistloopsshort

Java List<String> to Short


I have this list of string:

private final List<String> categoryList = Arrays.asList("27", "28, 96", "10", "15", "7", "98");

From the above list, "28, 96" is considered as one item (Not a typo). Converting each of them to short have no problems except for that one item:

for ( int m = 1; m < categoryList.size(); m++) {
    short layerValue = Short.parseShort(categoryList.get(m));
}

I'm getting this error converting the "28, 96":

java.lang.NumberFormatException: For input string: "28, 96"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Short.parseShort(Short.java:117)
    at java.lang.Short.parseShort(Short.java:143)

But if I add it directly:

//pmTPSelectList[0].layerRateList = new short[] {layerValue};
pmTPSelectList[0].layerRateList = new short[] {28, 96};

It works properly. So, I'm confused as to why it is and if there's a way to convert it as I need to loop a couple of values to replace the layervalue (Short)??? ty


Solution

  • You need to split that part up aswell in a second for loop

    for (String shortstr : categoryList) {
        String[] splitstr = shortstr.split(',');
        for (String innershort: splitstr) {
            short layerValue = Short.parseShort(innershort.trim());
            // add it to a list
        }
    }