Java LinkedHashMap gets first or last entry

I used LinkedHashMap because the order in which the keys on the map are entered is important.

But now I want to get the key value in the first place (the first entry entered) or the 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 !

Thank!

+120
java dictionary linkedhashmap
Dec 20 '09 at 17:54
source share
10 answers

The semantics of LinkedHashMap still apply to the map, not to LinkedList . It preserves the insertion order, yes, but this is a detail of the implementation, not an aspect of its interface.

The fastest way to get the "first" record is entrySet().iterator().next() . Getting the โ€œlastโ€ record is possible, but entails repeating the entire record by typing .next() until you reach the last. while (iterator.hasNext()) { lastElement = iterator.next() }

to change . However, if you're ready to go beyond the JavaSE API, Apache Commons Collections has its own LinkedMap , which has methods like firstKey and lastKey that do what you are looking for. The interface is much richer.

+141
Dec 20 '09 at 17:58
source share

Can you try to do something like (to get the latest entry):

 linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1]; 

this is O (N) :)

+19
Apr 19 '16 at 7:25
source share

LinkedHashMap The current implementation (Java 8) tracks its tail. If performance is a problem and / or the card is large, you can access this field through reflection.

Since the implementation may change, it's probably a good idea to have a fallback strategy. You might want to register something if you selected an exception so that you know that the implementation has changed.

It might look like this:

 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); } 
+11
Nov 27 '15 at 15:05
source share

Another way to get the first and last LinkedHashMap entry is to use the toArray method for the Set interface.

But I think that repeating the records in the recordset and getting the first and last record is the best approach.

Using array methods leads to the warning of the form "... requires a raw conversion to match ..." that cannot be fixed [but can only be suppressed using the @SuppressWarnings annotation ("checkbox")].

Here is a small example demonstrating the use of the toArray method:

 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 

+6
Dec 21 '09 at 5:12
source share

This is a bit dirty, but you can override the removeEldestEntry LinkedHashMap method, which may suit you as a private anonymous element:

 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; } }; 

This way you can always get the first entry in your eldest member. It will be updated every time you execute put .

It should also be easy to override put and install youngest ...

  @Override public Splat put(Integer key, Splat value) { youngest = value; return super.put(key, value); } 

All this breaks down when you start deleting records; didn't figure out how to do this.

It is very annoying that you cannot otherwise access the head or tail in a sensible way ...

+3
09 feb. '16 at 17:46
source share

Maybe 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; } 
+2
Mar 22 '13 at 0:03
source share

I would recommend using ConcurrentSkipListMap , which has firstKey() and lastKey() methods

+1
Sep 19
source share

Sentence:

 map.remove(map.keySet().iterator().next()); 
+1
Mar 31 '16 at 15:27
source share

Although linkedHashMap does not provide any method to get the first, last or any specific object.

But its pretty trivial to get:

  • Map orderMap = new LinkedHashMap ();
    Set al = orderMap.keySet ();

now uses an iterator on any object; You can get any object.

0
Nov 07 '12 at 7:14
source share

Yes, I encountered the same problem, but, fortunately, I only need the first element ... - This is what I did for this.

 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 - I would look at how to change the order of your map - save it in the temp variable, get access to the first element on the map with the reverse display (therefore, this will be your last element), kill the temporary variable.

Here are some good answers on how to change the hash map order:

How to iterate hashmap in reverse order in Java

If you are using the help from the link above, please let them know. :) Hope this helps someone.

0
Jul 26 '13 at 15:04 on
source share



All Articles