获取LinkedHashMap中的Previous键?

时间:2012-05-04 18:13:42

标签: java list linked-list linkedhashmap

我使用了LinkedHashMap lhmNotFinal,因为在map.i中输入的键的顺序很重要,使用这个来获取我的LinkedHashMap的值

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

现在我想得到我钥匙的先前价值,我该怎么做?提前谢谢你。

2 个答案:

答案 0 :(得分:2)

一般来说,这不是与LinkedHashMap相关的问题 - 它是一个编码问题。你可以做几件事:

String tmp= null;

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

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

答案 1 :(得分:2)

只是为了好玩:

//
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() );