sameer sameer - 1 month ago 5x
Java Question

Nested for loop over same Map in Java 8

Whats efficient way of implementing following pseduo-code for nested loop over same map in Java 8(where ordering is important)?

for (i = 0; i < n; ++i)
for (j = i + 1; j < n; ++j) {
process(Map[i], Map[j])

One inefficient way to do this is following:

List sortedKeyList = extra_sorted_keys(Map)
for (i = 0; i < sortedKeyList.length; ++i)
for (j = i + 1; j < sortedKeyList.length; ++j) {
i_elem = Map.get(sortedKeyList.get(i))
j_elem = Map.get(sortedKeyList.get(j))
process(i_elem, j_elem);

But I am looking for efficient nested iterations over same Java Map


If you need to process the map values by the ordering of the keys, I don’t think there is a more efficient way than the one you’re using in the question.

If you just need to process the values pairwise in any order, I would expect the following to be both readable and efficient.

    for (String iElem : yourMap.values()) {
        for (String jElem : yourMap.values()) {
            process(iElem, jElem);

If you’re really concerned about efficiency, you may try extracting values() to a local variable only once and see if you can measure any speedup.

Strictly speaking there is no general answer: it depends on your Map implementation. I would expect the above to hold true for most implementations, including those in java.util, but I could have missed something.