So i know how to iterate through a whole linkedhashmap from the beginning, but what if I want to only link through a certain portion from it? IE: i want to start from the end and go only 4 elements back. How would I do that and is it possible?
3 Answers
What you are searching for is a ListIterator which would allow you to iterate backwards in a list. Unfortunately, LinkedHashMap
does not hold a reference towards the previous element, and thus does not provide this iterator.
So, you end up with two solutions. One, you implement the method to find the X last elements: you hold, let's say an array (a circular buffer) of size X and keep there the last X elements you have seen. This solution is rather inefficient if you call this method frequently and for X much smaller than the size of your map.
A second solution is to keep a HashMap
instead of a LinkedHashMap
and an extra List
to maintain the insertion order. E.g. an ArrayList
or a LinkedList
which provide a ListIterator
and thus, backwards iteration.

- 417
- 3
- 9
You have to extend standard implementation and override methods that return appropriate iterator to your own.
Iterator<K> newKeyIterator() { return new KeyIterator(); }
Iterator<V> newValueIterator() { return new ValueIterator(); }
Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
LinkedHashMap.Entry
is a doubly linked list, so you can go forward and backward as well.
LinkedHashMap.LinkedHashIterator
is a base iterator for LinkedHashMap. Make what you need based on it.

- 4,175
- 15
- 31
You could use the ListIterator
for this, by doing something like this.
List list = new ArrayList<>(map.keySet());
ListIterator li = list.listIterator(list.size());
while (li.hasPrevious()) {
System.out.println(map.get(li.previous()));
}
Since the LinkedHashMap
maintains the order, you could simply create a list from the keys which are going to be in order as well. Get a ListIterator
from the last index, so that you can traverse backwards having a counter(which I've not shown) to iterator till the no. of elements required.

- 44,383
- 11
- 84
- 103