Search code examples
javadictionaryiterationlinkedhashmap

Going though a Map specifically a LinkedHashMap and retrieving both Key and Value using ForEach loop reversed


At the moment I'm looping though a list of messages that have the value of importance and the string of the message it's self using:

for(String MessageItem : MainEngine.mCurrentLevel.mNewsFeed.mMessageList.keySet())
{
     //Do message stuff here.
}

I have a problem in that only 10 messages can be displayed on screen and it needs to be from the most recent. Problem with the above is that it only shows from index 0 - 10. and no more.

Is there anyway to start from the top index and go in reverse using foreach?


Solution

  • You don't have to iterate through it. But it would be handy to pull the keys off and store it in a list. Thats the only way you can do indexOf() type operations.

    List<String> keyList = new ArrayList<String>(map.keySet());
    // Given 10th element's key
    String key = "aKey";
    int idx = keyList.indexOf(key);
    for ( int i = idx ; i >= 0 ; i-- ) 
    System.out.println(map.get(keyList.get(i)));
    

    for more details see answer by Kal