【问题标题】:HashMap iterator not starting with first key in collectionHashMap 迭代器不是从集合中的第一个键开始
【发布时间】:2016-02-05 12:20:15
【问题描述】:

我遇到了一个非常奇怪的情况,其中一个 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 专业知识的人可以伸出援助之手。

【问题讨论】:

    标签: java hashmap iterator


    【解决方案1】:

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

    【讨论】:

    • @ave8tor 可能类似于树状图...?喜欢...docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
    • 感谢您的帮助!原来我只需要使用 TreeMap 而不是 HashMap 来获得我想要的东西。答案如此简单,这让我很沮丧,我花了整整一周的空闲时间尝试一切可能的东西,以了解为什么它会以这种方式迭代它。
    • @SirDarius 感谢您的更正,这就是我的意思
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多