0

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?

Apprentice Programmer
  • 1,485
  • 4
  • 26
  • 39

3 Answers3

1

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.

nelly
  • 417
  • 3
  • 9
0

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.

Mikhail
  • 4,175
  • 15
  • 31
0

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.

Rahul
  • 44,383
  • 11
  • 84
  • 103