Java 8 includes some possible changes to HashSet/Map iteration order:
有些人可以建议我 – 我怎样才能以与插入顺序相同的顺序迭代Map中的对象,考虑到我仍然在我的开发环境中使用Java 1.8?
是的,当然HashMap从未保证可以按相同的顺序检索对象,但是它曾经在java 7中工作.
LinkedHashMap是否可以实现这一点?
解决方法
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering,which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.
有几次,我们还需要跨不同Java版本的可重复迭代顺序,LinkedHashMap工作正常.
TreeMap也是稳定迭代顺序的解决方案.当然,它具有对数操作时间(与LinkedHashMap中的常量相反),迭代顺序不是插入顺序而是键顺序:
The map is ordered according to the natural ordering of its keys,or by a Comparator typically provided at sorted map creation time.