1

i've got a LinkedHashMap and I'm double iterating over it as stated in the code below:

LinkedHashMap<Integer,Integer> nmResultMap = getResultMap();
float[][] results = new float[nmResultMap.size()][nmResultMap.size()];

    for (Entry<Integer,Integer> e :nmResultMap.entrySet()){
        for (Entry<Integer,Integer> t :nmResultMap.entrySet()){

            results[e.getValue()][t.getValue()] = doSomthng(e.getKey(),t.getKey());
        }
    }

This works fine, but since results is symmetric (doSomthng(e.getKey(),t.getKey())==doSomthng(t.getKey(),e.getKey())) I would like to save some runtime by starting the second iteration at the next (current+1) position of the first iteration like its easily possible with eg. Arrays:

for (int i  =0;i<array.length();i++){ 
    for (int j=i+1;j<array.length();j++){
        doSomthng(array[i][j]);
    }
}

Thank you for your help

Hellski
  • 65
  • 1
  • 7
  • This for syntax iterates on a whole collection; you will have to manually convert the data to a structure that allows random access and iterate yourself. You can also explicitely use iterators and manually advance them to the required positin. – Dariusz Jan 25 '13 at 13:36
  • What do you mean by "result is symmetric" ? Result will never be symmetric: https://ideone.com/9g5x3L , then which kind of optimization will not drop single, unique combinations ? You are probably doing something *strange* :> – Andrea Ligios Jan 25 '13 at 13:50
  • result of doSomthng(e.getKey(),t.getKey()) == doSomthng(t.getKey(),e.getKey()) – Hellski Jan 25 '13 at 15:39
  • +1 for sharing the formula (j=i+1) which is what I was looking for when I found this :-) – Stewart Jan 25 '13 at 20:45

2 Answers2

0

Convert the entrySet to an array, loop through this array:

Entry<Integer,Integer> entries = 
    nmResultMap.entrySet().toArray(new Entry<Integer,Integer>[0]);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Motivated through JB Nizet answer I'm using:

for (Entry<Integer,Integer> entry:h.getResultMap().entrySet()){
        nmResultList.add(entry);
    }
    float[][] results = new float[nmResultList.size()][nmResultList.size()];
    for (int i=0;i<nmResultList.size();i++){
        for (int j =i+1; j<nmResultList.size();j++){

            results[nmResultList.get(i).getValue()][nmResultList.get(j).getValue()] = doSomthng(h.data[nmMap.get(nmResultList.get(i).getKey())], h.data[nmMap.get(nmResultList.get(j).getKey())]);
        }
    }

which does exactly what I wanted, thanks a lot for your help.

Hellski
  • 65
  • 1
  • 7