Java LinkedHashMap get first or last entry
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.
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() }
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.
Can you try doing something like (to get the last entry):
linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];
I know that I came too late but I would like to offer some alternatives, not something extraordinary but some cases that none mentioned here. In case that someone doesn't care so much for efficiency but he wants something with more simplicity(perhaps find the last entry value with one line of code), all this will get quite simplified with the arrival of Java 8 . I provide some useful scenarios.
For the sake of the completeness, I compare these alternatives with the solution of arrays that already mentioned in this post by others users. I sum up all the cases and i think they would be useful(when performance does matter or no) especially for new developers, always depends on the matter of each problem
Possible Alternatives
Usage of Array Method
I took it from the previous answer to to make the follow comparisons. This solution belongs @feresr.
public static String FindLasstEntryWithArrayMethod() { return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]); }
Usage of ArrayList Method
Similar to the first solution with a little bit different performance
public static String FindLasstEntryWithArrayListMethod() { List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet()); return entryList.get(entryList.size() - 1).getValue(); }
Reduce Method
This method will reduce the set of elements until getting the last element of stream. In addition, it will return only deterministic results
public static String FindLasstEntryWithReduceMethod() { return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue(); }
SkipFunction Method
This method will get the last element of the stream by simply skipping all the elements before it
public static String FindLasstEntryWithSkipFunctionMethod() { final long count = linkedmap.entrySet().stream().count(); return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue(); }
Iterable Alternative
Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too
public static String FindLasstEntryWithGuavaIterable() { return Iterables.getLast(linkedmap.entrySet()).getValue(); }
Here is the full source code
import com.google.common.collect.Iterables;import java.math.BigDecimal;import java.math.RoundingMode;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;public class PerformanceTest { private static long startTime; private static long endTime; private static LinkedHashMap<Integer, String> linkedmap; public static void main(String[] args) { linkedmap = new LinkedHashMap<Integer, String>(); linkedmap.put(12, "Chaitanya"); linkedmap.put(2, "Rahul"); linkedmap.put(7, "Singh"); linkedmap.put(49, "Ajeet"); linkedmap.put(76, "Anuj"); //call a useless action so that the caching occurs before the jobs starts. linkedmap.entrySet().forEach(x -> {}); startTime = System.nanoTime(); FindLasstEntryWithArrayListMethod(); endTime = System.nanoTime(); System.out.println("FindLasstEntryWithArrayListMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds"); startTime = System.nanoTime(); FindLasstEntryWithArrayMethod(); endTime = System.nanoTime(); System.out.println("FindLasstEntryWithArrayMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds"); startTime = System.nanoTime(); FindLasstEntryWithReduceMethod(); endTime = System.nanoTime(); System.out.println("FindLasstEntryWithReduceMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds"); startTime = System.nanoTime(); FindLasstEntryWithSkipFunctionMethod(); endTime = System.nanoTime(); System.out.println("FindLasstEntryWithSkipFunctionMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds"); startTime = System.currentTimeMillis(); FindLasstEntryWithGuavaIterable(); endTime = System.currentTimeMillis(); System.out.println("FindLasstEntryWithGuavaIterable : " + "took " + (endTime - startTime) + " milliseconds"); } public static String FindLasstEntryWithReduceMethod() { return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue(); } public static String FindLasstEntryWithSkipFunctionMethod() { final long count = linkedmap.entrySet().stream().count(); return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue(); } public static String FindLasstEntryWithGuavaIterable() { return Iterables.getLast(linkedmap.entrySet()).getValue(); } public static String FindLasstEntryWithArrayListMethod() { List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet()); return entryList.get(entryList.size() - 1).getValue(); } public static String FindLasstEntryWithArrayMethod() { return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]); }}
Here is the output with performance of each method
FindLasstEntryWithArrayListMethod : took 0.162 millisecondsFindLasstEntryWithArrayMethod : took 0.025 millisecondsFindLasstEntryWithReduceMethod : took 2.776 millisecondsFindLasstEntryWithSkipFunctionMethod : took 3.396 millisecondsFindLasstEntryWithGuavaIterable : took 11 milliseconds