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