Wassim Sboui
Wassim Sboui

Reputation: 1820

Get the previous key in a LinkedHashMap?

I have used LinkedHashMap<String, Integer> lhmNotFinal because it is important the order in which keys entered in the map. I get the value of my LinkedHashMap using this:

for (String key:lhmNotFinal.keySet())
{
    System.out.println(key);
}

Now, I want to get the previous value of my key, how can I do that?

Upvotes: 1

Views: 3463

Answers (2)

Thomas Uhrig
Thomas Uhrig

Reputation: 31605

It's not a problem related with a LinkedHashMap in general - it's a coding problem. You can do several things:

String tmp= null;

for (String key : lhmNotFinal.keySet()) {

    tmp = key ;    // after the first iteration you have your last key in tmp
}

Upvotes: 3

Omnaest
Omnaest

Reputation: 3096

Just for the fun:

//
Map<String, String> map = new LinkedHashMap<String, String>();
map.put( "key1", "value1" );
map.put( "key2", "value2" );

//
final ListIterator<String> keyListIterator = new ArrayList<String>( map.keySet() ).listIterator();
assertEquals( "key1", keyListIterator.next() );
assertEquals( "key2", keyListIterator.next() );
assertEquals( "key2", keyListIterator.previous() );
assertEquals( "key1", keyListIterator.previous() );
assertEquals( "key1", keyListIterator.next() );
assertEquals( "key2", keyListIterator.next() );

Upvotes: 3

Related Questions