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

使用HashMap迭代器遇空行触发NoSuchElementException问题求助

问题描述

我正在进行ArrayList与HashMap的相关训练,使用BufferedReader解析文件并将每行内容存入ArrayList,随后创建HashMap<String,Integer>,以ArrayList的元素为键,行号为值。使用Lambda表达式打印键值对一切正常,但使用Iterator将键值存入变量时,触发了NoSuchElementException异常。删除文件中的空行后则运行正常,请问我哪里操作有误?

代码示例
String sourceFile = "newtestfile.txt";
BufferedReader br = new BufferedReader(new FileReader(sourceFile));
String line = br.readLine();
ArrayList<String> readListe = new ArrayList<>();  

while(line != null){
    readListe.add(line);
    line = br.readLine();
}

HashMap<String,Integer> map = new HashMap<>();
for(int i = 0; i<readListe.size() ;i++){
    map.put(readListe.get(i), i+1);
}

//map.forEach((k,v) -> System.out.println(k));
Iterator<Map.Entry<String,Integer>> iterator2 = map.entrySet().iterator();
while(iterator2.hasNext()){
    String key = iterator2.next().getKey();
    int value = iterator2.next().getValue();

    System.out.println(key + " " + value);
}
源文件内容
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren
NewLine ipsum dolor sit amet, consetetur sadipscing elitr, 
This is line 3

John Doe
问题原因与解决方法

错误原因

你的Iterator使用逻辑有误:每次调用iterator2.next()都会让迭代器指针向后移动一位。在while循环中,你连续调用了两次next()——一次拿key,一次拿value,这意味着每次循环会消耗两个Entry元素。

当文件包含空行时,ArrayList里有5个元素(对应5个Map Entry),是奇数。循环执行两次后,已经消耗了4个元素,第三次循环时hasNext()判断还剩1个元素,但你又调用两次next(),第二次调用就会触发NoSuchElementException(因为已经没有元素可以取了)。而删除空行后,元素总数是4个(偶数),两次循环刚好消耗完所有元素,所以不会报错。

修正代码

只需要调用一次next()获取当前Entry,再从中提取key和value:

Iterator<Map.Entry<String,Integer>> iterator2 = map.entrySet().iterator();
while(iterator2.hasNext()){
    Map.Entry<String,Integer> entry = iterator2.next();
    String key = entry.getKey();
    int value = entry.getValue();

    System.out.println(key + " " + value);
}

额外提醒:HashMap是无序的,如果你需要保留行号的顺序,建议使用LinkedHashMap代替HashMap,这样迭代时会按照元素插入的顺序输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:50:24