HashMap迭代器不以集合

时间:2016-02-05 12:20:16

标签: 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专业知识的人可以伸出援助之手。

1 个答案:

答案 0 :(得分:1)

您假设HashMaps以某个给定顺序返回其条目是错误的。使用OrderedMap的实现,例如TreeMap