Question

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

Was it helpful?

Solution

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

Entry<Integer,Integer> entries = 
    nmResultMap.entrySet().toArray(new Entry<Integer,Integer>[0]);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top