3

I have a LinkedHashMap (because the order of entry is important). I want to be able to iterate over it's entries (key, value pairs) like an array from end to start so the foreach methods doesn't fit here something like :

for (int i = DestIndexStartPair.entrySet().size() , i> 0 ; i--) {
    entry = DestIndexStartPair.entrySet()[i];
    String Endsection = output.substring(entry.value());
    System.out.println(Endsection );
}
darijan
  • 9,725
  • 25
  • 38
LordTitiKaka
  • 2,087
  • 2
  • 31
  • 51

4 Answers4

4

There is no efficient way to iterate over a Set (such as entrySet) in reverse order. If you need iteration in both directions, then for the opposite direction the best approach is to copy into a temporary list and iterate the list in reverse.

Of course, if you only need one direction, then you should just ensure the LinkedHashMap has that order instead of the opposite.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

Working solution:

List<Entry<Foo,Bar>> list = new ArrayList<Entry<Foo,Bar>>(map.entries());

for (int i = list.size() - 1; i >= 0; i--) {
    Entry<Foo,Bar> entry = list.get(i);
}

Obviously, the trade off here is that you have to copy the whole map into the array list. If your map is too big (whatever is too big), you might have performance and memory problems.

rufushuang
  • 302
  • 4
  • 17
darijan
  • 9,725
  • 25
  • 38
2

Looking at map implementation might help more. May be by overriding in more appropriate way this can be achieved in balanced way as in performance or thread safety etc. But here is small hack that may help,

public class HackedLinkedHashMap<K,V> extends LinkedHashMap<K,V> implements Map<K,V> {

private LinkedList<K> keyList = new LinkedList<>();

@Override
public V put(K key, V value){
    V obj = super.put(key, value);
    keyList.addFirst(key);

    return obj;
}

public LinkedList<K> getReversedKeyList(){
    return keyList;
}}


public static void main(String[] args) {
    System.out.println("Test conference");
    HackedLinkedHashMap<Integer, Integer> map = new HackedLinkedHashMap();
    for(Integer i=0;i<100;i++){
        map.put(i, i);
    }   
    Iterator<Integer> iterator = map.getReversedKeyList().iterator();
    while (iterator.hasNext()){
        System.out.println(iterator.next());
    }
}
Saurabh
  • 445
  • 6
  • 19
0

An EntrySet is a Set and thus doesn't normally have an index.

So, what you need would be...

for(Entry<K,V> entry : DestIndexStartPair.entrySet()) {
    String Endsection = output.substring(entry.value()); // whatever output is
    System.out.println(Endsection );
}

...and then store the result, and reverse it.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58