问题描述
我已使用,因为键在地图中输入的顺序很重要。
I have used LinkedHashMap
because it is important the order in which keys entered in the map.
但是现在我想要获取值的首要位置(第一次输入)或最后一个。
But now I want to get the value of key in the first place (the first entered entry) or the last.
应该有一个方法,如 first()
和 last()
或类似的东西
Should there be a method like first()
and last()
or something like that?
我需要一个迭代器才能得到第一个关键条目?这就是为什么我使用!
Do I need to have an iterator to just get the first key entry? That is why I used LinkedHashMap
!
谢谢!
推荐答案
LinkedHashMap 仍然是一个Map,而不是一个 LinkedList
。它保留插入顺序,是的,但这是一个实现细节,而不是其界面的一个方面。
The semantics of LinkedHashMap
are still those of a Map, rather than that of a LinkedList
. It retains insertion order, yes, but that's an implementation detail, rather than an aspect of its interface.
获取第一个条目的最快方法仍然是的entrySet()。迭代器()。下一个()
。获得最后条目是可能的,但是将需要通过调用 .next()
来遍历整个条目集,直到到达最后一个条目。 while(iterator.hasNext()){lastElement = iterator.next()}
The quickest way to get the "first" entry is still entrySet().iterator().next()
. Getting the "last" entry is possible, but will entail iterating over the whole entry set by calling .next()
until you reach the last. while (iterator.hasNext()) { lastElement = iterator.next() }
/ strong>:但是,如果您愿意超越JavaSE API,请有自己的实现,其方法如和,这样做你正在寻找。界面相当丰富。
edit: However, if you're willing to go beyond the JavaSE API, Apache Commons Collections has its own LinkedMap
implementation, which has methods like firstKey
and lastKey
, which do what you're looking for. The interface is considerably richer.
这篇关于Java LinkedHashMap获取第一个或最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!