简体   繁体   English

Java中的ArrayList到HashMaps

[英]ArrayList to HashMaps in Java

I am trying to get values from an ArrayList that is sorted and want to store it in a HashMap , where the values of the ArrayList become keys of the HashMap . 我试图从排序的ArrayList中获取值,并希望将其存储在HashMap ,其中ArrayList的值成为HashMap键。 Will the order of the values in the HashMap still be the same as that of ArrayList ? HashMap中的值的顺序是否仍然与ArrayList的顺序相同?

No. Use a TreeMap instead. 不。使用TreeMap代替。 This will preserve the order of insertion. 这将保留插入顺序。

HashMap makes no guarantees as to the order the mappings are stored or iterated, so simply running through the ArrayList and putting them into the HashMap as keys will very likely result in unordered iterations. HashMap不保证映射存储或迭代的顺序,因此简单地运行ArrayList并将它们作为键放入HashMap很可能会导致无序迭代。

As others have pointed out, LinkedHashMap does preserve insertion order for iterations. 正如其他人所指出的,LinkedHashMap确实保留了迭代的插入顺序 An additional run of insertions will result in unordered iterations again, though. 但是,额外的插入运行将导致无序迭代。 Both HashMap and LinkedHashMap support constant time lookup - LinkedHashMap pays for its extra feature in space (by maintaining pointers between the keys). HashMap和LinkedHashMap都支持恒定时间查找 - LinkedHashMap支付其在空间中的额外功能(通过维护键之间的指针)。

As others have also pointed out, TreeMap preserves order after updates, so this might be a better option for you, or not. 正如其他人也指出的那样,TreeMap会在更新后保留订单,因此这对您来说可能是更好的选择。 Of course, if the ArrayList is sorted with a specific Comparator, you must feed that same Comparator to the TreeMap on construction for the sorting to be the same. 当然,如果使用特定的Comparator对ArrayList进行排序,则必须在构造时将同一个Comparator提供给TreeMap,以使排序相同。 Note that TreeMap does not have constant time lookup, due to being implemented as a Red-Black search tree. 请注意,由于实现为红黑搜索树,TreeMap没有恒定的时间查找。

As your ArrayList has been ordered, no need to use a TreeMap because this will compare to order again and it's not necessary. 由于您的ArrayList已经订购,因此无需使用TreeMap,因为这将再次与订单进行比较,而且没有必要。 You should use a LinkedHashMap that will keep the exact order of your ArrayList when you put your value in. 您应该使用LinkedHashMap,它会在您输入值时保持ArrayList的确切顺序。

Check This: Insert Values of ArrayList into HashMap 检查: 将ArrayList的值插入HashMap

HashMap<String, Item> itemMap = new HashMap<String, Item>();

for (Item item : itemList) 
{
   itemMap.put(item.getitemCode(), item);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM