TheLexoPlexx
TheLexoPlexx

Reputation: 117

More Efficient way to avoid two for-loops and combine them into one?

Basically, I got this:

(path is a String Array)

    String writer = "";
    for (int i = 0; i < path.length; i++) {
        writer += path[i] + "{";
    }
    writer += string;
    for (int i = 0; i < path.length; i++) {
        writer += "}";
    }

But this looks ugly and inefficient. Is there any way to properly combine this into only one for-loop?

Upvotes: 0

Views: 125

Answers (2)

Lothar
Lothar

Reputation: 5459

Here is a solution without a for-loop and with the usage of StringBuilder instead of +=-constructs which can lead to memory- and performance problems.

StringBuilder firstPart = new StringBuilder();
StringBuilder lastPart = new StringBuilder();

Arrays.stream(path)
    .forEach(elem -> {
        firstPart.append(elem);
        firstPart.append("{");
        lastPart.append("}");
    });

firstPart.append(string);
firstPart.append(lastPart.toString());
String writer = firstPart.toString();

Upvotes: 5

Joop Eggen
Joop Eggen

Reputation: 109623

With no smart means, the following has more speed:

StringBuilder sb = new StringBuilder();
for (String p : path) { // Might cost a bit of speed.
    sb.append(p).append('{');
}
sb.append(string);
for (int i = 0; i < path.length; ++i) {
    sb.append('}');
}
String writer = sb.toString();

In one loop:

StringBuilder sb = new StringBuilder(string);
for (int i = path.length - 1; i >= 0; --i) {
    sb.insert(0, '{');
    sb.insert(0, path[i]);
    sb.append('}');
}
String writer = sb.toString();

Upvotes: 3

Related Questions