This example shows how to get the first or last entry of the LinkedHashMap in Java. The example also shows how to remove the first or last entry of the LinkedHashMap using various ways.
How to get the first or last entry of the LinkedHashMap in Java?
The LinkedHashMap class is an implementation of the hash table and linked list of the Map interface. It maintains the references to the head and tail of the list, but it is internal and not exposed via any methods. However, there are several ways using which you can get the first or last entry of the LinkedHashMap in Java.
1. Using Iterator
Since there is no exposed method to access the first or last element of the LinkedHashMap, iterating the LinkedHashMap object will be the simplest solution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class LinkedHashMapGetFirstLastEntriesExample { public static void main(String[] args) { LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); lhmap.put(1, "One"); lhmap.put(2, "Two"); lhmap.put(3, "Three"); lhmap.put(4, "Four"); lhmap.put(5, "Five"); //get all entries of the LinkedHashMap Set<Map.Entry<Integer, String>> entries = lhmap.entrySet(); //get the iterator for entries Iterator<Map.Entry<Integer, String>> iterator = entries.iterator(); Map.Entry<Integer, String> entry = null, firstEntry = null, lastEntry = null; //iterate through the entries while(iterator.hasNext()){ entry = iterator.next(); //this will be null only first time if(firstEntry == null) firstEntry = entry; //this will have last entry after iteration is over lastEntry = entry; } System.out.println("First Entry: " + firstEntry); System.out.println("Last Entry: " + lastEntry); } } |
Output
1 2 |
First Entry: 1=One Last Entry: 5=Five |
If you want to remove the first entry or last entry from the map, you can use below given code after the while loop.
1 2 3 4 5 6 7 |
//remove first entry lhmap.remove(firstEntry.getKey()); //remove last entry lhmap.remove(lastEntry.getKey()); System.out.println("LinkedHashMap contains: " + lhmap); |
Output
1 2 3 |
First Entry: 1=One Last Entry: 5=Five LinkedHashMap contains: {2=Two, 3=Three, 4=Four} |
Note: This approach requires you to iterate the whole map object and may not perform if the map is too large.
2. By converting it to an array
You can get all keys of the LinkedHashMap object using the keySet
method and then convert it to an array using the toArray
method. Once you get an array of keys, you can access the first and last key of the LinkedHashMap using the array index as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); lhmap.put(1, "One"); lhmap.put(2, "Two"); lhmap.put(3, "Three"); lhmap.put(4, "Four"); lhmap.put(5, "Five"); /* * Get all keys from the LinkedHashMap and convert * it to an array */ Integer[] arrayKeys = lhmap.keySet().toArray( new Integer[ lhmap.size() ] ); if(arrayKeys.length > 0 ){ //first key is at 0 index System.out.println("First key: " + arrayKeys[0]); //last keys is at array length - 1 index System.out.println("Last key: " + arrayKeys[ arrayKeys.length - 1 ]); //get first value using the first key System.out.println( "First value: " + lhmap.get(arrayKeys[0]) ); //get last value using the last key System.out.println( "Last value: " + lhmap.get(arrayKeys[ arrayKeys.length - 1 ]) ); } |
Output
1 2 3 4 |
First key: 1 Last key: 5 First value: One Last value: Five |
Note: This approach requires the allocation of a new array which is costly operation especially if the map is large. Iterating through the map is better in that case.
3. By converting it an ArrayList or LinkedList
Instead of an array, you can also convert the key set to an ArrayList or LinkedList.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* * Get all keys from the LinkedHashMap and convert * it to an ArrayList */ List<Integer> listKeys = new ArrayList<Integer>(lhmap.keySet()); if(listKeys.size() > 0 ){ System.out.println("First key: " + listKeys.get(0)); System.out.println("First value: " + lhmap.get(listKeys.get(0))); System.out.println("Last key: " + listKeys.get( listKeys.size() - 1 )); System.out.println("Last value: " + lhmap.get(listKeys.get( listKeys.size() - 1 ))); } |
Output
1 2 3 4 |
First key: 1 First value: One Last key: 5 Last value: Five |
The LinkedList class provides the getFirst
and getLast
methods to access the first and last element respectively. You can use that too.
1 2 3 4 5 6 7 8 9 |
LinkedList<Integer> listKeys = new LinkedList<Integer>(lhmap.keySet()); if(listKeys.size() > 0 ){ System.out.println("First key: " + listKeys.getFirst()); System.out.println("First value: " + lhmap.get( listKeys.getFirst() )); System.out.println("Last key: " + listKeys.getLast()); System.out.println("Last value: " + lhmap.get( listKeys.getLast()) ); } |
Output
1 2 3 4 |
First key: 1 First value: One Last key: 5 Last value: Five |
Note: Same as an array approach, this approach needs to allocate memory for new ArrayList or LinkedList object which is costly in terms of performance.
4. Using the reflection
This option is just for the educational purpose, you should not use this in production. The LinkedHashMap class maintains the first and last entry in member variables named head and tail respectively, but they are private to the class. To access these fields, we need to make them accessible using the reflection API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); lhmap.put(1, "One"); lhmap.put(2, "Two"); lhmap.put(3, "Three"); lhmap.put(4, "Four"); lhmap.put(5, "Five"); try{ //get the internal private field "head" Field firstEntry = lhmap.getClass().getDeclaredField("head"); //make it accessible firstEntry.setAccessible(true); //access it! System.out.println("First entry: " + firstEntry.get(lhmap)); //get the internal private field "tail" Field lastEntry = lhmap.getClass().getDeclaredField("tail"); //make it accessible lastEntry.setAccessible(true); //access it! System.out.println("Last entry: " + lastEntry.get(lhmap)); }catch(Exception e){ e.printStackTrace(); } |
Output
1 2 |
First entry: 1=One Last entry: 5=Five |
This example is a part of the LinkedHashMap in Java Tutorial.
Please let me know your views in the comments section below.
References:
Java 8 LinkedHashMap