Java LinkedHashMap 获取第一个或最后一个条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1936462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java LinkedHashMap get first or last entry
提问by maiky
I have used LinkedHashMap
because it is important the order in which keys entered in the map.
我已经使用了,LinkedHashMap
因为在地图中输入键的顺序很重要。
But now I want to get the value of key in the first place (the first entered entry) or the last.
但是现在我想首先获取 key 的值(第一个输入的条目)或最后一个。
Should there be a method like first()
and last()
or something like that?
是否应该有类似first()
和last()
或类似的方法?
Do I need to have an iterator to just get the first key entry? That is why I used LinkedHashMap
!
我是否需要一个迭代器来获取第一个键条目?这就是我使用的原因LinkedHashMap
!
Thanks!
谢谢!
采纳答案by skaffman
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.
的语义LinkedHashMap
仍然是 Map的语义,而不是 a的语义LinkedList
。它保留插入顺序,是的,但这是一个实现细节,而不是其接口的一个方面。
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() }
获得“第一个”条目的最快方法仍然是entrySet().iterator().next()
. 获取“最后一个”条目是可能的,但需要通过调用迭代整个条目集,.next()
直到到达最后一个。 while (iterator.hasNext()) { lastElement = iterator.next() }
edit: However, if you're willing to go beyond the JavaSE API, Apache Commons Collectionshas its own LinkedMap
implementation, which has methods like firstKey
and lastKey
, which do what you're looking for. The interface is considerably richer.
编辑:但是,如果您愿意超越 JavaSE API,Apache Commons Collections有它自己的LinkedMap
实现,它具有firstKey
和 之类的方法lastKey
,可以满足您的需求。界面相当丰富。
回答by sateesh
One more way to get first and last entry of a LinkedHashMap is to use "toArray" method of Set interface.
获取 LinkedHashMap 的第一个和最后一个条目的另一种方法是使用 Set 接口的“toArray”方法。
But I think iterating over the entries in the entry set and getting the first and last entry is a better approach.
但我认为迭代条目集中的条目并获取第一个和最后一个条目是更好的方法。
The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")].
数组方法的使用导致“...需要未经检查的转换以符合...”形式的警告,该警告无法修复[但只能通过使用注释@SuppressWarnings("unchecked")]来抑制。
Here is a small example to demonstrate the usage of "toArray" method:
下面是一个小例子来演示“toArray”方法的用法:
public static void main(final String[] args) {
final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
orderMap.put(6, "Six");
orderMap.put(7, "Seven");
orderMap.put(3, "Three");
orderMap.put(100, "Hundered");
orderMap.put(10, "Ten");
final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
final int maplength = mapValues.size();
final Entry<Integer,String>[] test = new Entry[maplength];
mapValues.toArray(test);
System.out.print("First Key:"+test[0].getKey());
System.out.println(" First Value:"+test[0].getValue());
System.out.print("Last Key:"+test[maplength-1].getKey());
System.out.println(" Last Value:"+test[maplength-1].getValue());
}
// the output geneated is :
First Key:6 First Value:Six
Last Key:10 Last Value:Ten
public static void main(final String[] args) {
final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
orderMap.put(6, "Six");
orderMap.put(7, "Seven");
orderMap.put(3, "Three");
orderMap.put(100, "Hundered");
orderMap.put(10, "Ten");
final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
final int maplength = mapValues.size();
final Entry<Integer,String>[] test = new Entry[maplength];
mapValues.toArray(test);
System.out.print("First Key:"+test[0].getKey());
System.out.println(" First Value:"+test[0].getValue());
System.out.print("Last Key:"+test[maplength-1].getKey());
System.out.println(" Last Value:"+test[maplength-1].getValue());
}
// the output geneated is :
First Key:6 First Value:Six
Last Key:10 Last Value:Ten
回答by Doua Beri
I would recommend using ConcurrentSkipListMapwhich has firstKey()
and lastKey()
methods
我建议使用具有和方法的ConcurrentSkipListMapfirstKey()
lastKey()
回答by rai.skumar
Though linkedHashMap doesn't provide any method to get first, last or any specific object.
尽管linkedHashMap 不提供任何方法来获取第一个、最后一个或任何特定对象。
But its pretty trivial to get :
但它很容易得到:
- Map orderMap = new LinkedHashMap();
Set al = orderMap.keySet();
- 映射 orderMap = new LinkedHashMap();
Set al = orderMap.keySet();
now using iterator on al object ; you can get any object.
现在在 al 对象上使用迭代器;你可以得到任何对象。
回答by user2127649
Perhaps something like this :
也许是这样的:
LinkedHashMap<Integer, String> myMap;
public String getFirstKey() {
String out = null;
for (int key : myMap.keySet()) {
out = myMap.get(key);
break;
}
return out;
}
public String getLastKey() {
String out = null;
for (int key : myMap.keySet()) {
out = myMap.get(key);
}
return out;
}
回答by ryvianstyron
Yea I came across the same problem, but luckily I only need the first element... - This is what I did for it.
是的,我遇到了同样的问题,但幸运的是我只需要第一个元素...... - 这就是我为它所做的。
private String getDefaultPlayerType()
{
String defaultPlayerType = "";
for(LinkedHashMap.Entry<String,Integer> entry : getLeagueByName(currentLeague).getStatisticsOrder().entrySet())
{
defaultPlayerType = entry.getKey();
break;
}
return defaultPlayerType;
}
If you need the last element as well - I'd look into how to reverse the order of your map - store it in a temp variable, access the first element in the reversed map(therefore it would be your last element), kill the temp variable.
如果您还需要最后一个元素 - 我会研究如何反转地图的顺序 - 将其存储在临时变量中,访问反转地图中的第一个元素(因此它将是您的最后一个元素),杀死温度变量。
Here's some good answers on how to reverse order a hashmap:
以下是有关如何对哈希图进行反向排序的一些很好的答案:
How to iterate hashmap in reverse order in Java
If you use help from the above link, please give them up-votes :) Hope this can help someone.
如果您使用上述链接的帮助,请给他们投票 :) 希望这可以帮助某人。
回答by assylias
LinkedHashMap
current implementation (Java 8) keeps track of its tail. If performance is a concern and/or the map is large in size, you could access that field via reflection.
LinkedHashMap
当前实现(Java 8)会跟踪它的尾部。如果性能是一个问题和/或地图尺寸很大,您可以通过反射访问该字段。
Because the implementation may change it is probably a good idea to have a fallback strategy too. You may want to log something if an exception is thrown so you know that the implementation has changed.
因为实现可能会改变,所以也有一个后备策略可能是一个好主意。如果抛出异常,您可能想要记录一些内容,以便您知道实现已更改。
It could look like:
它可能看起来像:
public static <K, V> Entry<K, V> getFirst(Map<K, V> map) {
if (map.isEmpty()) return null;
return map.entrySet().iterator().next();
}
public static <K, V> Entry<K, V> getLast(Map<K, V> map) {
try {
if (map instanceof LinkedHashMap) return getLastViaReflection(map);
} catch (Exception ignore) { }
return getLastByIterating(map);
}
private static <K, V> Entry<K, V> getLastByIterating(Map<K, V> map) {
Entry<K, V> last = null;
for (Entry<K, V> e : map.entrySet()) last = e;
return last;
}
private static <K, V> Entry<K, V> getLastViaReflection(Map<K, V> map) throws NoSuchFieldException, IllegalAccessException {
Field tail = map.getClass().getDeclaredField("tail");
tail.setAccessible(true);
return (Entry<K, V>) tail.get(map);
}
回答by robert
It's a bit dirty, but you can override the removeEldestEntry
method of LinkedHashMap, which it might suit you to do as a private anonymous member:
这有点脏,但是您可以覆盖removeEldestEntry
LinkedHashMap的方法,它可能适合您作为私有匿名成员执行:
private Splat eldest = null;
private LinkedHashMap<Integer, Splat> pastFutures = new LinkedHashMap<Integer, Splat>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Splat> eldest) {
eldest = eldest.getValue();
return false;
}
};
So you will always be able to get the first entry at your eldest
member. It will be updated every time you perform a put
.
因此,您将始终能够在您的eldest
会员处获得第一个条目。每次执行put
.
It should also be easy to override put
and set youngest
...
它也应该很容易覆盖put
和设置youngest
......
@Override
public Splat put(Integer key, Splat value) {
youngest = value;
return super.put(key, value);
}
It all breaks down when you start removing entries though; haven't figured out a way to kludge that.
但是,当您开始删除条目时,一切都会崩溃;还没有想出一种方法来解决这个问题。
It's very annoying that you can't otherwise get access to head or tail in a sensible way ...
非常烦人的是,您无法以合理的方式访问头部或尾部......
回答by Tadeu Jr.
Suggestion:
建议:
map.remove(map.keySet().iterator().next());
回答by FRR
Can you try doing something like (to get the last entry):
你可以尝试做一些类似的事情(以获得最后一个条目):
linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];