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

Java集合拼接功能无输出问题求助

问题排查与修复:集合拼接操作无输出

核心问题原因

你的代码中文件读取逻辑过滤了空行,导致用于区分集合A和B的分隔空行被丢弃,最终setB始终为空集合,拼接操作自然没有输出内容。

具体细节:

  • readSetFromFile方法中,对每一行执行line.trim()后,通过if (!line.isEmpty())跳过了空行,没有将空行加入返回列表。
  • main方法依赖空行切换readingA状态来拆分A、B集合,空行被过滤后,readingA始终为true,所有行都被加入setA,setB一直是空集合。

修复方案

修改readSetFromFile方法,保留空行作为A、B集合的分隔标志,不要过滤空行:

private static List<String> readSetFromFile(String fileName) {
    List<String> s = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            s.add(line); // 保留所有行,包括trim后为空的行
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return s;
}

main方法中的拆分逻辑无需修改,保持原判断即可:

for(String line:setsUnion){
    if(line.equals("")){
        readingA = false;
    } else{
        if(readingA){
            setA.add(line);
        }else{
            setB.add(line);
        }
    }
}

额外优化建议

  1. 若需求要求集合元素唯一,拼接操作可改用LinkedHashSet自动去重:
private static List<String> concatenate(List<String> setA, List<String> setB) {
    Set<String> tempSet = new LinkedHashSet<>();
    for (String a : setA) {
        for (String b : setB) {
            tempSet.add(a + b);
        }
    }
    return new ArrayList<>(tempSet);
}
  1. 可添加setB非空判断,避免无意义的空结果输出。

验证示例

若输入文件Pro-1_Example.txt格式如下:

a
b

c
d

修复后setA为["a","b"],setB为["c","d"],拼接操作会输出["ac","ad","bc","bd"],结果正常显示。

内容的提问来源于stack exchange,提问作者Mr.roboto0104

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:10:10