You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将String ArrayList转为Integer ArrayList?转换时遇NumberFormatException求助

Hey there! Let's break down why your code is throwing that NumberFormatException and fix it up.

What's causing the error?

The exception happens because one or more strings in your sample list can't be converted to a valid integer. Common culprits include:

  • Strings with letters, symbols, or decimal points (like "123a" or "45.67")
  • Empty strings or strings with only whitespace
  • Strings with hidden invisible characters (like tabs or newlines)
  • Numbers formatted with thousand separators (like "1,234")

First step: Identify the problematic string

Before fixing, let's find exactly which string is breaking things. Add a quick print/debug log to your loop:

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

for (String fav : sample) {
    System.out.println("Attempting to parse: '" + fav + "'"); // Print the string being parsed
    try {
        sample2.add(Integer.parseInt(fav));
    } catch (NumberFormatException e) {
        System.err.println("Failed to parse: '" + fav + "'");
        e.printStackTrace();
    }
}

This will show you exactly which value is causing the crash.

Solutions based on your needs

Option 1: Skip invalid values (if allowed by your business logic)

Clean up the string first (trim whitespace) and use a regex to check if it's a valid integer before parsing:

List<Integer> sample2 = new ArrayList<>();
for (String fav : sample) {
    String cleanedStr = fav.trim();
    // Regex matches positive/negative integers (no decimals, letters, etc.)
    if (cleanedStr.matches("-?\\d+")) {
        sample2.add(Integer.parseInt(cleanedStr));
    } else {
        System.err.println("Skipping invalid integer string: '" + fav + "'");
    }
}

Option 2: Handle exceptions gracefully (assign default values)

If you need to keep every position in the list, catch the exception and set a default value (like 0) instead of crashing:

List<Integer> sample2 = new ArrayList<>();
for (String fav : sample) {
    try {
        sample2.add(Integer.parseInt(fav.trim()));
    } catch (NumberFormatException e) {
        // Assign a default value, or add custom logic here
        sample2.add(0);
        System.err.println("Invalid integer: '" + fav + "' → using default value 0");
    }
}

Option 3: Use Java 8+ streams for cleaner code

If you're using Java 8 or later, streams make this more concise:

import java.util.stream.Collectors;

// Filter out invalid values and parse valid ones
List<Integer> sample2 = sample.stream()
    .map(String::trim)
    .filter(s -> s.matches("-?\\d+"))
    .map(Integer::parseInt)
    .collect(Collectors.toList());

Bonus: Handle formatted numbers (like "1,234")

If your strings have thousand separators, use NumberFormat instead of Integer.parseInt:

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

List<Integer> sample2 = new ArrayList<>();
NumberFormat numberFormat = NumberFormat.getInstance(Locale.US); // Match your region's format

for (String fav : sample) {
    try {
        Number number = numberFormat.parse(fav.trim());
        sample2.add(number.intValue());
    } catch (ParseException e) {
        System.err.println("Failed to parse formatted number: '" + fav + "'");
    }
}

内容的提问来源于stack exchange,提问作者Franklyn Omeben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:47:41