Iterating over LinkedHashMap in reverse order

I have LinkedHashMap

(because the order of the input is important). I want to be able to iterate over records (key, value pairs) such as an array from to the end , so foreach methods don'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 );
}

      

+3


source to share


4 answers


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 deal is that you have to copy the entire map into a list of arrays. If your card is too large (which is too large), you may have performance and memory issues.

+2


source


In reverse order, there is no efficient way to iterate over Set

(for example entrySet

). If you need to iterate in both directions, then in the opposite direction, the best way is to copy into a temporary list and repeat the list in reverse order.



Of course, if you only need one direction, then you should simply ensure that LinkedHashMap

it has that order instead of the opposite.

+4


source


Looking at the map implementation can help. It may be more appropriate to achieve this in a balanced way, as with performance or thread safety etc. But here's a little hack that might 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());
    }
}

      

+2


source


EntrySet is a Set and therefore usually has no index.

So, you would need ...

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

      

... and then save the result and discard it.

0


source







All Articles