0

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?

2 Answers 2

2

You cannot directly iterate a LinkedHashMap in reverse order. The APIs don't allow it.

The best you can do is copy the keys (or the key/value pairs) to an array and then iterate the array in reverse order.

(Writing the code is simple ... and I encourage you to do it yourself!)

1

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.