简体   繁体   中英

How to convert a String ArrayList to an Integer ArrayList?

I am trying to convert a string arraylist to an integer arraylist but it crashes my app giving error as a NumberFormatException , please any help will be appriciated.

List<String> sample = new ArrayList<String>(set2);
List<Integer> sample2 = new ArrayList<Integer>(sample.size());
for (String fav : sample) {
    sample2.add(Integer.parseInt(fav));
}

Try this method every time you add to your list to make sure you are adding just numeric Strings (Strings that are represented with chars from '0'-'9'.)

public static boolean isNumeric(String strNum) {
    if (strNum == null) {
        return false;
    }
    try {
        double d = Double.parseDouble(strNum);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

So your code would look like:

List<String> sample = new ArrayList<String>(set2);
List<Integer> sample2 = new ArrayList<Integer>(sample.size());
for (String fav : sample) {
    if (isNumeric(fav))
        sample2.add(Integer.parseInt(fav));
}

This should get you away without exceptions.

in this code I added this code fav.chars().allMatch( Character::isDigit ) to check whether all character of a String text is a digit number of not and if its true then it will be add to sample2 array:

List<String> sample = new ArrayList<String>(set2);

List<Integer> sample2 = new ArrayList<Integer>(sample.size());
for (String fav : sample) {
    if(fav.chars().allMatch( Character::isDigit )) {
        sample2.add(Integer.parseInt(fav));
    }
}

You can filter out those strings that contain non-digit characters to avoid this error:

List<String> sample = List.of("123", "235", "abc!", "  ");
List<Integer> sample2 = sample.stream()
        .filter(str -> str.codePoints()
                // all characters are digits
                .allMatch(Character::isDigit))
        .map(Integer::parseInt)
        .collect(Collectors.toList());

System.out.println(sample2); // [123, 235]

According to your code:

  • First thing is how can you be sure that all the string in the sample array are integers. If you'r certain they are integers then your code is fine. And as it is a app you dont need it to crash so properly swallowing exceptions are fine in my view (unless your properly logging what happened).

  • So a best way if possible is using List<Integer> list (restricting non integer values in the first place). But if string is required then you can check if it can be parsed first and then add it to the list ie If only parse exceptions need to be avoided. Hope this made sense.

APPROACH 1 (recommended if list initial list size doesn't matter):

    public static void main(String[] args){
        List<String> sample=new ArrayList<>(Arrays.asList("1","2","non-integer")); //here the non-integer throws a number format exception but the try catch block catches it and returns 0;

        List<Integer> sample2=new ArrayList<>(sample.size());

        for (String fav:sample){
            if ( isIntegerParseable(fav) ) {                 
                sample2.add(Integer.parseInt(fav));
            }
        }
        // sample2 output is : [1, 2]
    }
    


    private static boolean isIntegerParseable(String fav) {
        try{
            if(fav == null) return false;
            Integer.parseInt(fav);
            return true;
        }catch (NumberFormatException nfe){
            //logg this error ( the following value is not a number);
        }
        return false;
    }

APPROACH 2 (NOT RECCOMENDED) :

    public static void main(String[] args){
        List<String> sample=new ArrayList<>(Arrays.asList("1","2","non-integer")); //here the non-integer throws a number format exception but the try catch block catches it and returns 0;
    
        List<Integer> sample2=new ArrayList<>(sample.size());
    
        for (String fav:sample){
             sample2.add(toIntOrDefault(fav));
        }
        // "If you are returning a null then [1, 2, null] but returning null is even risky as it may result NPE"
        // sample2 output is : [1, 2, 0]
    }
    private static int toIntOrDefault(String value){
        try{
            return Integer.parseInt(value);
        }catch (NumberFormatException nfe){
            //logg this error ( the following value is not a number);
            // may throw your custom exceptions if any or default value in this case
        }
        return 0; //you can even return null and change return type to Integer as you are using List<Integer> which is an object type list.
    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM