FidelCashflo
FidelCashflo

Reputation: 533

Combining two for loops into one

I'm trying to find a better way to execute this method.

private void appendTiles(StringBuilder builder, String taggedRefData) {
    for (List<Line> column : columns) {
        for (Line line : column) {
            builder.append(line.link).append(line.text);
        }
    }
}

Is there a more efficient way of doing this?

Upvotes: 0

Views: 646

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

No, there is no way to optimize this further in a meaningful way: the code of appendTiles must walk all Line objects inside columns, despite the fact that the actual objects are inside a two-dimensional structure (a collection of Lists). One way or the other, you have to access line.link and line.text. This is the "payload" of the method; it is not going to change, even if you manage to combine two loops into one by using streams.

Upvotes: 2

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

No, you have a list of lists, there will always be two loops. Even in Java 8 you could use streams and flatMap, which would still use 2 loops, just internally.

Upvotes: 2

Related Questions