-3

is it possible to retrieve the next (next, as in the next key value which has been inserted) key value of a LinkedHashMap?
E.g. the current key value is 2 and the next key value is 4. I want to use the value of the next key without setting my iterator (or whatsoever) one index further. Apparently using one iterator doesn't seem to do the job. Another idea would be to cast the set returned by myHashMap.keySet() to some other implementing class but I am not sure if it is possible to retrieve the next element.

Any ideas?

optional
  • 2,504
  • 4
  • 18
  • 30
  • Seeing as I use a LinkedHashMap I would define next as the next key value. – optional Jul 09 '15 at 16:30
  • The public API does not offer a way to do this in O(1). The `Iterator` from `keySet` is your best bet, but you have to traverse it all the way to your key, then get the `next` if there is one. – Sotirios Delimanolis Jul 09 '15 at 16:38
  • Nevermind, I solved it this way: `LinkedList linkedList = new LinkedList<>(); linkedList.addAll(myHashMap.keySet());` which works perfectly fine for me and preserves the order. – optional Jul 09 '15 at 16:40
  • That is exactly equivalent to the key set `Iterator`. Instead of traversing the iterator, you traverse the linked list. (Except now you copy everything over to another data structure.) `LinkedList` access is O(n). – Sotirios Delimanolis Jul 09 '15 at 16:43
  • I never asked for a O(1) solution and no that wouldn't work. I want a peekable `Iterator`. As stated in my question, it isn't possible with only one iterator. – optional Jul 09 '15 at 16:45
  • Why do you not want to fetch the next one? Just use it as the current one in the next iteration. – Dragan Bozanovic Jul 09 '15 at 16:47

1 Answers1

0

Assume there is LinkedHashMap<K,V> linkHashMap, now define a custom method getNextKey which takes a parameter index and return the next index value if valid.

Code snippet (not working code)-

public K getNextKey(int index){
    // put check if index is valid
    K[] keyArray = linkedHasMap.keySet.toArray(new K[linkedHasMap.size()]);
    return K[index+1];
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103