java - HashMap 迭代器不从集合中的第一个键开始

标签 java hashmap iterator

我遇到了一个非常奇怪的情况,其中 HashMap 变量

HashMap<Integer, String> locationCatalog = new HashMap<>();

将正确迭代(即从第一个数字键开始),有时则不然。我正在迭代 Excel 文档(使用外部库)来获取单元格值,并根据单元格的行和列坐标将其放入 HashMap 中。

locationCatalog.put(row.getRowNum(), cell.getStringCellValue().trim());

填充所有数据后,我迭代 locationCatalog 来获取内容:

Set set = locationCatalog.entrySet();
Iterator trimIterator = set.iterator();
System.out.println(lastLabelName + " - locationCatalog contents (run #1):");
while (trimIterator.hasNext()) {
    Map.Entry locationMap = (Map.Entry)trimIterator.next();
    System.out.println("Key: " + (int) locationMap.getKey() + ", Row: " + ((int) locationMap.getKey() + 1) + ", Location: " + locationMap.getValue().toString());
    ...
}

这是一次良好运行的打印结果:

BALI - locationCatalog contents (run #1):
Key: 16, Row: 17, Location: S082025 E1150531
Key: 17, Row: 18, Location: S082025 E1150531
Key: 18, Row: 19, Location: 
Key: 19, Row: 20, Location: S082025 E1150531
Key: 20, Row: 21, Location:
Key: 21, Row: 22, Location: S082025 E1150531

异常情况偶尔发生。似乎是从我移动单元格而不是仅仅复制和粘贴内容开始的。弄清楚这一点后,我调整了 put 方法,仅使用独立于 Excel 源的常规整数。不过,这一调整并没有改变结果。这是一个糟糕的运行示例:

BALI - locationCatalog contents (run #1):
Key: 16, Row: 17, Location: S08 20 25 E115 05 31 
Key: 17, Row: 18, Location: 
Key: 18, Row: 19, Location: 
Key: 9, Row: 10, Location: S08 20 25 E115 05 31
Key: 10, Row: 11, Location: S08 20 25 E115 05 31
Key: 11, Row: 12, Location: 
Key: 12, Row: 13, Location: S08 20 25 E115 05 31
Key: 13, Row: 14, Location: 
Key: 14, Row: 15, Location: S08 20 25 E115 05 31
Key: 15, Row: 16, Location: S08 20 25 E115 05 31

由于无法发布 Excel 文件的屏幕截图,因此此运行的单元格从第 10 行开始并继续到第 19 行。但是,当它经历 locationCatalog 的迭代时,它不会从最低的键开始,在本例中为键 9。这是一个问题,因为我必须多次迭代此 HashMap 才能获得最终产品,并且需要按升序排列。完成收集后,我将其清除并开始用一组新数据填充它。

如果我将相同的单元格剪切并粘贴到不同的行中,结果(正确)将更改为:

BALI - locationCatalog contents (run #1):
Key: 4, Row: 5, Location: S08 20 25 E115 05 31
Key: 5, Row: 6, Location: S08 20 25 E115 05 31
Key: 6, Row: 7, Location: 
Key: 7, Row: 8, Location: S08 20 25 E115 05 31
Key: 8, Row: 9, Location: 
Key: 9, Row: 10, Location: S08 20 25 E115 05 31
Key: 10, Row: 11, Location: S08 20 25 E115 05 31
Key: 11, Row: 12, Location: S08 20 25 E115 05 31
Key: 12, Row: 13, Location: 
Key: 13, Row: 14, Location: 

我已经尝试了一周来弄清楚发生了什么,包括更改 HashMap 的参数,但都没有成功。希望有更多脑力和 Java 专业知识的人能够伸出援手。

最佳答案

您认为 HashMaps 按给定顺序返回其条目的假设是错误的。请改用 OrderedMap 的实现,例如 TreeMap

关于java - HashMap 迭代器不从集合中的第一个键开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35224107/

相关文章:

java - 为什么 GregorianCalendar.getInstance 包含儒略历类型的 calsys 和 cdate

java - Spring事务配置减去Exception (`-Exception`)的含义

Java:从非静态比较器对其外部类字段的引用

rust - 转置表的 btreemap 与 hashmap

Java循环链表 headless 无尾?

c++ - 错误 : 'e' is not a class, 命名空间或枚举

java - 在 Spring 中销毁的 Session 上调用 Listener 类中的服务层函数

hashmap - 为什么 csv::Reader 记录中的字符串在插入到 HashMap 中时生命周期不够长?

java - 是否可以通过其位置从 HashMap 中获取元素?

python - 让python迭代器倒退?