Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I iterate this map in reverse direction

Tags:

java

This is my map with iterators to remove some data based on some conditions, now I want to run the same map in reverse direction and conditions accordingly.

But I couldn't find any ListIterator to go back easily.

How Can I go about this ?

Also the Map implementation I am using is a TreeMap

for(int i=countIteration;i<(countIteration+2);i++)
{
    Iterator it = imageFilexxSm.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        if(pairs.getKey().equals(data1.get(i).replace(".png", ".mp3")))  
        {
            it.remove();
        }
    }

    Iterator itr = imageFilexxS.entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry pairsx = (Map.Entry)itr.next();
        if(pairsx.getKey().equals(data1.get(i)))     
        {
            System.out.println("entry deleted."+pairsx.getKey());
            itr.remove();
        }
    }
}
like image 340
Prateek Avatar asked Dec 01 '22 19:12

Prateek


1 Answers

TreeMap has a descendingMap method (note that it returns a view on the original map, it does not copy it):

//iterate over the entry set in reverse order
for (Map.Entry<X,Y> e : map.descendingMap().entrySet()) {
    X key = e.getKey();
    Y value = e.getValue();
}
like image 185
assylias Avatar answered Dec 24 '22 02:12

assylias